我正在清理一些现有代码。
Sheets("Control").Select
MyDir = Cells(2, 1)
CopySheet = Cells(6, 2)
MyFileName = Dir(MyDir & "wp*.xls")
' when the loop breaks, we know that any subsequent call to Dir implies
' that the file need to be added to the list
While MyFileName <> LastFileName
MyFileName = Dir
Wend
MyFileName = Dir
While MyFileName <> ""
Cells(LastRow + 1, 1) = MyFileName
LastRow = LastRow + 1
MyFileName = Dir
Wend
我的问题涉及到
Dir
返回结果,如果对结果的顺序有任何保证。使用时
董事
在上述循环中,代码意味着
董事
按名称排序。
除非
董事
保证这一点,这是一个需要修复的错误。问题是,Dir()是否保证了文件返回的顺序,或者它是隐式的?
解决方案
基于@Frederic的回答,这是我想出的解决方案。
使用这个
quicksort algorithm
连词和一个函数
returns all files in a folder
...
Dim allFiles As Variant
allFiles = GetFileList(MyDir & "wp*.xls")
If IsArray(allFiles) Then
Call QuickSort(allFiles, LBound(allFiles), UBound(allFiles))
End If
Dim x As Integer
Dim lstFile As String
x = 1
' still need to loop through results to get lastFile
While lstFile <> LastFileName
lstFile = allFiles(x)
x = x + 1
Wend
For i = x To UBound(allFiles)
MyFileName = allFiles(i)
Cells(LastRow + 1, 1) = MyFileName
LastRow = LastRow + 1
Next i