指定要通过Excel / VBA循环的其他目录

时间:2012-04-24 17:35:26

标签: excel vba loops excel-vba directory

我使用文件系统对象循环遍历一组目录,我想指定一个要循环的其他目录。例如,我目前有:

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

但是,我想指定一个要循环的附加文件夹,例如:

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

或者,是否可以在循环命令中指定多个对象,例如:

For Each objSubfolder in colSubfolders, "additionalpath"

1 个答案:

答案 0 :(得分:3)

最简单的方法是打破枚举目录的代码和“采取某些操作”的代码,并将其包装在重复所需内容的调用中;

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