excel - Dir() 对返回的文件的顺序有任何保证吗?

标签 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

我的问题涉及 Dir 如何返回结果以及结果的顺序是否有任何保证。当在上面的循环中使用 Dir 时,代码意味着对 Dir 的最终调用按名称排序。

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

解决方案

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

使用这个quicksort algorithm结合和一个函数 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 documentation甚至说:

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.

关于excel - Dir() 对返回的文件的顺序有任何保证吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4282940/

相关文章:

excel - 从 Excel 更新 MS Word 页脚表中的页码

ms-access - 如何在VB中获得上个月的开始和结束

excel - 如何让 Excel 在 VBA 中使用时间切片器自动选择最近一周?

excel - 如何用 "th"和 "nd"结尾替换 Excel 中的数字列?

mysql - 自动化 excel 表格下载、修改和上传到 MySQL 数据库

vba - VBA中具有多个非连续列的范围索引

vba - MS Outlook 2010 .SenderEmailAddress 返回一个巨大的字符串

windows - 如何让vba文件自行删除

vba - 如何将 String 变量的值插入到将出现在电子邮件正文中的某些文本中?

vb.net - 用户完成后关闭 Excel