0

I'm looping through a directory and grabbing certain files that begin with a certain substring. I would prefer to loop in the order that the files are displayed in the directory, however, when looping and outputting each file name, it iterates to a file not in the next slot of the directory order. Does anyone have an explanation for this? My looping schema is as follows:

'open template file
Set templDoc = Documents.Open(tFile)

strFile = Dir$(strFolder & "16.*.doc")        ' can change to .docx

Count = 0

Do Until strFile = ""
    Count = Count + 1
    Set rng = templDoc.Range
    MsgBox strFile
    With rng
        .Collapse wdCollapseEnd
        If Count > 1 Then
            .InsertBreak wdSectionBreakNextPage
            .End = templDoc.Range.End
            .Collapse wdCollapseEnd
        End If
        .InsertFile strFolder & strFile
    End With
    strFile = Dir$()
Loop

Directory queue is: 16.2.1, 16.2.3.1, 16.2.3.2...

Looping order is: 16.2.1, 16.2.10, 16.2.11...

Clearly sorts them differently, but is there way to specify looping in "directory order" sort of say?

newuser2967
  • 316
  • 1
  • 4
  • 15
  • How are the files displayed/sorted in the directory? By last modified time, filename? – BigBen Feb 21 '20 at 20:08
  • 1
    `Dir` is unsorted. see tip [HERE](https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/dir-function) – Scott Craner Feb 21 '20 at 20:10
  • see: https://stackoverflow.com/questions/4282940/does-dir-make-any-guarantee-on-the-order-of-files-returned – Scott Craner Feb 21 '20 at 20:16
  • Ah!, thanks Scott this is the answer I was looking for. Doesn't guarantee order, perfect. So, send file names to an array and sort it first, then iterate through the sorted array. This is perfect. – user2599674 Feb 21 '20 at 20:45

0 Answers0