我正在尝试清理一些现有代码
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
时,代码意味着对 Dir
的最终调用按名称排序。
除非 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
最佳答案
不保证 Dir()
会按任何特定顺序返回文件。 MS Access VBA documentation甚至说:
Tip Because file names are retrieved in no particular order, you may want to store returned file names in an
array
, and then sort the array.
关于excel - Dir() 对返回的文件的顺序有任何保证吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4282940/