Dir() 对返回的文件顺序有任何保证吗? [英] Does Dir() make any guarantee on the order of files returned?
问题描述
我正在尝试清理一些现有的代码
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
我的问题与 Dir
如何返回结果以及是否对结果顺序有任何保证有关.当在上述循环中使用 Dir
时,代码暗示对 Dir
的结果调用按名称排序.
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() 对返回文件的顺序有任何保证还是隐含的?
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?
基于@Frederic 的回答,这是我想出的解决方案.
Based on @Frederic's answer, this is the solution I came up with.
结合使用这个快速排序算法和一个返回文件夹中的所有文件 ...
Using this quicksort algorithm in 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
推荐答案
不保证 Dir()
会以任何特定顺序返回文件.MS Access VBA 文档 甚至说:
There's no guarantee that Dir()
will return the files in any particular order. The MS Access VBA documentation even says:
提示 因为文件名是没有特定的顺序检索,你可能想要存储返回的文件名在 array
中,然后对数组进行排序.
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.
这篇关于Dir() 对返回的文件顺序有任何保证吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!