关于VBA中的
DIR
中返回文件的序号是不可控的,其中可以看下官方对于
DIR
的描述
如果想实现重新排序,可以通过自定义的VBA函数
Sub Sorting(list As Variant)
Dim coll As Object
Set coll = CreateObject("System.Collections.ArrayList")
For Each Item In list
coll.Add Item
' Sort
coll.Sort
Debug.Print vbCrLf & "Sorted Ascending"
' Add this sub from "Reading through the items" section
PrintToImmediateWindow coll
' Reverse sort
coll.Reverse
Debug.Print vbCrLf & "Sorted Descending"
PrintToImmediateWindow coll
End Sub
Sub PrintToImmediateWindow(coll As Object)
Dim i As Long
For i = 0 To coll.Count - 1
Debug.Print coll(i)
Next i
End Sub
示例代码
Sub Test()
Dim allFiles() As Variant
MyDir = "C:\Users\xx\Downloads\CopyTest\Result\"
Count = 0
Filename = Dir(MyDir)
Do While Filename <> ""
Debug.Print Filename
ReDim Preserve allFiles(Count)