Link to home
Start Free TrialLog in
Avatar of IT_Crowd
IT_CrowdFlag for Heard Island and McDonald Islands

asked on

Word VBA Code to Traverse Files in a Folder Alphabetically

I have a macro that traverses two folder structures, checks for Word documents within those folder structures and outputs the results to a text file. These output files are then referenced in customized tabs within Word.

Unfortunately, these folders are not showing up within Word as "sorted alphabetically". I've verified that Windows explorer is seeing these folders and files sorted alphabetically, but is there a way to force the VBA code to see or sort the folders in alpha order?

I have attached some segments of code along with an example of the output and end result. Thanks for the help!!
CreateTemplates-Macro.txt
ExampleOutput.txt
Tab-Drop-Down.png
Avatar of Rgonzo1971
Rgonzo1971

HI,

you could use a collection to sort it

Sub gg()
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objBaseTemplateFolder = _
        objFSO.getfolder("C:\Task Lists") '
    Set cFldr = New Collection
    For Each folder In objBaseTemplateFolder.Subfolders
        cFldr.Add folder.Name, folder.Name
    Next
    For i = 1 To cFldr.Count - 1
        For J = i + 1 To cFldr.Count
            If UCase(cFldr(i)) > UCase(cFldr(J)) Then
               vTemp = cFldr(J)
               cFldr.Remove J
               cFldr.Add vTemp, vTemp, i
            End If
        Next J
    Next i

    'Test it
    For Each Itm In cFldr
        Debug.Print Itm
    Next Itm
End Sub

Open in new window

Regards
ASKER CERTIFIED SOLUTION
Avatar of aikimark
aikimark
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of IT_Crowd

ASKER

Thanks for the ideas.  I'm really like the dir command idea right now, I think it will be pretty easy to work with, and I think my code could use a rework anyways.
I'll use the DIR command in VBA to get the results I want.  Thanks!
If you omit the /b flag from the DIR command, you can use the following regexp patterns to parse the results.  The first one gives you directory matches and the second one parses the docx/docm file names within each match.
Directory of ([^\r]*)\s+((?:.|\n)*?)\d bytes
\d.{36}\d (.*?\.doc[xm])

Open in new window