Dir()是否对返回的文件的顺序提供任何保证? [英] Does Dir() make any guarantee on the order of files returned?
问题描述
我正在清理一些现有的代码
表格(控制)。选择
pre>
MyDir =单元格(2,1)
CopySheet =单元格(6,2)
MyFileName = Dir(MyDir&wp * .xls)
'我们知道任何后续调用Dir意味着
'该文件需要添加到列表
而MyFileName& LastFileName
MyFileName = Dir
Wend
MyFileName = Dir
虽然MyFileName<>
细胞(LastRow + 1,1)= MyFileName
LastRow = LastRow + 1
MyFileName = Dir
Wend
我的问题与
Dir
如何返回结果以及结果顺序有任何保证。当在上面的循环中使用Dir
时,代码意味着结果调用Dir
按名称排序。
除非
Dir
保证这是一个需要修复的错误。问题是,Dir()是否对文件的返回顺序进行任何保证?是否隐藏?
解决方案
基于@ Frederic的答案,这是我想出的解决方案。
使用此快速排序算法连结和功能,返回文件夹中的所有文件 ...
Dim allFiles As Variant
allFiles = GetFileList(MyDir&wp * .xls)
如果IsArray allFiles)然后
调用QuickSort(allFiles,LBound(allFiles),UBound(allFiles))
End If
Dim x As Integer
Dim lstFile As String
x = 1
'仍然需要循环结果才能获得lastFile
虽然lstFile<> LastFileName
lstFile = allFiles(x)
x = x + 1
Wend
对于i = x到UBound(allFiles)
MyFileName = allFiles )
单元格(LastRow + 1,1)= MyFileName
LastRow = LastRow + 1
Next i
解决方案不能保证
Dir()
将以任何特定的顺序返回文件。 MS Access VBA文档甚至说:
提示因为文件名是
,没有特定的顺序,您可以
在数组
中存储返回的文件名
,然后将
存储在数组中。
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 usingDir
in a loop as above, the code implies that the resultant calls toDir
are ordered by name.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?Solution
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
解决方案There's no guarantee that
Dir()
will return the files in any particular order. The MS Access VBA documentation even says: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屋!