Dir()是否对退回的文件的顺序做出任何保证?

Ahm*_*mad 13 excel vba

我正在尝试清理一些现有的代码

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
Run Code Online (Sandbox Code Playgroud)

我的问题涉及Dir退货结果以及结果顺序是否有任何保证.当Dir在上面的循环中使用时,代码暗示结果调用Dir按名称排序.

除非Dir保证这一点,否则这是一个需要修复的错误.问题是,Dir()是否对返回文件的顺序做出了任何保证,还是隐含的?

根据@ Frederic的回答,这是我提出的解决方案.

结合使用此快速排序算法返回文件夹中所有文件的函数...

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
Run Code Online (Sandbox Code Playgroud)

Fré*_*idi 8

无法保证Dir()以任何特定顺序返回文件.在MS访问VBA文档甚至说:

提示因为文件名没有按特定顺序检索,您可能希望将返回的文件名存储在一个array,然后对该数组进行排序.