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

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

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的结果调用按名称sorting。

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

基于@弗雷德里克的答案,这是我想出的解决scheme。

结合使用这种快速sortingalgorithm和返回文件夹中所有文件的function…

 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文档甚至说:

提示由于文件名是以特定顺序检索的,因此可能需要将返回的文件名存储在array ,然后对数组进行sorting。