VBA 遍历子文件夹以打开多个文件

VBA loop through subfolders to open multiple files

我有一个代码允许我搜索文件路径和多个子文件夹以打开一个文件,但是我希望能够打开多个名称略有不同的文件,例如 effect00001.dat 或 effect00014.dat 但是我不太确定如何

我的代码是:

Sub LoopSubfoldersAndFiles()
    Dim fso As Object
    Dim Folder As Object
    Dim subfolders As Object
    Dim MyFile As String
    Dim wb As Workbook
    Dim CurrFile As Object

With Application
    .ScreenUpdating = False
    .EnableEvents = False
    .Calculation = xlCalculationManual
End With

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set Folder = fso.GetFolder("\My Documents\Output files\analysis-tool-development")
    Set subfolders = Folder.subfolders
    MyFile = "effect00001.dat"

    For Each subfolders In subfolders

    Set CurrFile = subfolders.Files

        For Each CurrFile In CurrFile
            If CurrFile.Name = MyFile Then
                Set wb = Workbooks.Open(subfolders.Path & "\" & MyFile)
            End If
        Next

    Next

    Set fso = Nothing
    Set Folder = Nothing
    Set subfolders = Nothing

With Application
    .EnableEvents = True
    .Calculation = xlCalculationAutomatic
    .ScreenUpdating = True
End With

End Sub

替换行

If CurrFile.Name = MyFile Then

来自

If CurrFile.Name Like MyFile Then

然后您可以将 wildcards 用于 MyFile


编辑:

我也觉得行

Set wb = Workbooks.Open(subfolders.Path & "\" & MyFile)

应替换为

Workbooks.Open(subfolders.Path & "\" & MyFile)

因为 wb 值立即被另一个值替换,并且未被使用。