Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify Additional Directory to Loop Through Excel/VBA

I am looping through a set of directories using a File System Object, and I want to specify an additional directory to loop through. For example, I currently have:

Sub test()
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFolder = objFSO.GetFolder(Directory)
    Set colSubfolders = objFolder.Subfolders
    For Each objSubfolder In colSubfolders
        ' take some action
    End For
End Sub

But, I want to specify an additional folder to loop through, such as:

colSubfolders = colSubfolders + "additionalpath"
For Each objSubfolder In colSubfolders ....

Alternatively, is it possible to specify multiple objects in a loop command, such as:

For Each objSubfolder in colSubfolders, "additionalpath"
like image 750
mike Avatar asked Jun 18 '26 01:06

mike


1 Answers

Simplest way is to break out the code that enumerates the directories and the code that "takes some action" and wrap it in a call that repeats what you need;

Sub foo()
    enumDirs "c:\temp\", "c:\music", "c:\as many as you like ..."
End Sub

Sub enumDirs(ParamArray strPaths() As Variant)
    Dim i As Long
    For i = 0 To UBound(strPaths)
        enumDir CStr(strPaths(i))
    Next
End Sub

Sub enumDir(strPath As String)
    Dim objFolder As Object, colSubfolders As Object, objSubfolder As Object
    Set objFolder = CreateObject("Scripting.FileSystemObject").GetFolder(strPath)
    Set colSubfolders = objFolder.Subfolders
    For Each objSubfolder In colSubfolders
        TakeSomeAction strPath, objSubfolder.Name
    Next
End Sub

sub TakeSomeAction(strRoot As String, strFoundPath As String)
    Debug.Print ">"; strRoot & ", " & strFoundPath
End sub
like image 79
Alex K. Avatar answered Jun 19 '26 18:06

Alex K.