代码之家  ›  专栏  ›  技术社区  ›  Ahmad

Dir()是否保证返回文件的顺序?

  •  12
  • Ahmad  · 技术社区  · 14 年前

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

    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()是否保证了文件返回的顺序,或者它是隐式的?

    解决方案

    基于@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
    
    1 回复  |  直到 8 年前
        1
  •  8
  •   Frédéric Hamidi    14 年前

    不能保证 Dir() 将按任何特定顺序返回文件。这个 MS Access VBA documentation 甚至说:

    小费 因为文件名是 没有特别的顺序,你 可能要存储返回的文件名 在一个 array ,然后 对数组排序。