Does Dir() make any guarantee on the order of files returned?

calendar_today Asked Nov 26, 2010
thumb_up 6 upvotes
history Updated April 16, 2026

Question posted 2010 · +8 upvotes

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 using Dir in a loop as above, the code implies that the resultant calls to Dir 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

Accepted answer +6 upvotes

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.

Top vba Q&A (6)

+6 upvotes ranks this answer #66 out of 81 vba solutions on this site .
vba