Loop through subfolders in a folder using Dir

Do some process on the subfolders in a folder

The code below shows how you can process the subfolders in a folder.

If you look at the code you see that only the first time Dir has the FileSpec argument. This first call returns the first file. Subsequent calls, inside the loop, retrieve extra filenames, until an empty string is returned meaning there are no more files to process.


    'TODO: specify folder to loop subfolders for
    Dim strFolder As String: strFolder = "C:\temp\"
    Dim strItemInFolder As String
    strItemInFolder = Dir(strFolder, vbDirectory)
    Do While strItemInFolder <> ""
        If ((GetAttr(strFolder & strItemInFolder) And vbDirectory) = vbDirectory) And _
            Not (strItemInFolder = "." Or strItemInFolder = "") Then
            'TODO: replace Debug.Print by the process you want to do on the subfolder
            'Dim strFilePath As String: strFilePath = strFolder & strItemInFolder
            Debug.Print strItemInFolder
        End If
        strItemInFolder = Dir
    Loop

Create array of subfolders for a given folder

In the code below the filenames are stored in an array. This allows you to separate the specific activity of processing from the activity of finding the subfolders to process using Dir.


Dim strFolder As String: strFolder = "C:\temp\"
Dim strItemInFolder As String
Dim FolderList() As String 'The array with found folders
Dim intFoundFolders As Integer
strItemInFolder = Dir(strFolder, vbDirectory)
Do While strItemInFolder <> ""
    If ((GetAttr(strFolder & strItemInFolder) And vbDirectory) = vbDirectory) And _
        Not (strItemInFolder = "." Or strItemInFolder = "..") Then
            ReDim Preserve FolderList(intFoundFolders)
            FolderList(intFoundFolders) = strItemInFolder
            intFoundFolders = intFoundFolders + 1
    End If
    strItemInFolder = Dir
Loop