遍历文件夹中的子文件夹

时间:2019-10-15 19:34:17

标签: excel vba

我从另一个问题中获得了此代码,并正在尝试对其进行自定义。

我收到错误消息

  

运行时错误'1004':对象'工作簿'的方法'打开'失败。

我想使用主文件夹的路径来遍历该文件夹中的所有(子)文件夹。这些子文件夹不包含其他子文件夹。

我想打开文件名中具有子字符串“ -WB_”的每个Excel文件,然后进行编辑(此代码中看到的编辑只是一个占位符,以查看其是否有效)。我使用InStr尝试确定CurrFile.Name是否包含“ -WB _”。

我有一个想法是CurrFile.Name没有提供字符串,所以当我尝试使用Workbooks.Open时不起作用。

我拿出我的真实路径名,并用“通往主文件夹的路径”替换了它,以保护我的真实姓名。

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
    Dim fileName As String
    Dim pathName As String

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

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder("PATH TO MAIN FOLDER")
    Set subfolders = folder.subfolders
    pathName = "PATH TO MAIN FOLDER"

    For Each subfolders In subfolders

        Set CurrFile = subfolders.Files

        For Each CurrFile In CurrFile
            fileName = CurrFile.Name
            If InStr(CurrFile.Name, "-WB_") Then
                Workbooks.Open (pathName & fileName)
                Workbooks(CurrFile.Name).Sheets(1).Range("a1:a20") = "Excel"
                wb.Close SaveChanges:=True
            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

0 个答案:

没有答案