vba Dir() 对返回文件的顺序有任何保证吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4282940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does Dir() make any guarantee on the order of files returned?
提问by Ahmad
I am trying to clean up some existing code
我正在尝试清理一些现有的代码
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
My question relates to how Dir
returns results and if there are any guarantees on the order of results. When using Dir
in a loop as above, the code implies that the resultant calls to Dir
are ordered by name.
我的问题涉及如何Dir
返回结果以及是否对结果顺序有任何保证。Dir
在上述循环中使用时,代码暗示对结果的调用Dir
按名称排序。
Unless Dir
guarantees this, it's a bug which needs to be fixed. The question, does Dir() make any guarantee on the order in which files are returned or is it implicit?
除非Dir
保证这一点,否则这是一个需要修复的错误。问题是, Dir() 是否对返回文件的顺序有任何保证,还是隐含的?
Solution
解决方案
Based on @Frederic's answer, this is the solution I came up with.
根据@Frederic 的回答,这是我想出的解决方案。
Using this quicksort algorithmin conjunction and a function that 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
采纳答案by Frédéric Hamidi
There's no guarantee that Dir()
will return the files in any particular order. The MS Access VBA documentationeven says:
不能保证Dir()
会以任何特定顺序返回文件。在MS访问VBA文档甚至说:
TipBecause file names are retrieved in no particular order, you may want to store returned file names in an
array
, and then sort the array.
提示因为文件名的检索没有特定的顺序,所以您可能希望将返回的文件名存储在 中
array
,然后对数组进行排序。