遍历每个工作簿vba中的工作簿和工作表

Des*_*ond 2 excel vba excel-vba

我想遍历文件夹中的所有工作簿,然后遍历每个工作簿的所有工作表.我有下面的代码,但目前问题在于For Each ws in StrFile.Sheets:

Sub LoopThroughFiles()
    Dim StrFile As String
    StrFile = Dir("C:\Users\A9900899\Desktop\bob\VBAProject\Raw\")
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        For Each ws In StrFile.Sheets
            Debug.Print ws.Name
        Next ws
        StrFile = Dir
    Loop
End Sub
Run Code Online (Sandbox Code Playgroud)

这里我的错误是什么?

Sha*_*ado 5

为了遍历Workbook.Sheets你需要的所有Set wb当前StrFile,然后循环wb.Sheets.

使用Application.ScreenUpdating = FalseApplication.DisplayAlerts = False将最小化所有屏幕闪烁和Excel警报.

Option Explicit

Sub LoopThroughFiles()

    Dim StrFile As Variant
    Dim fPath As String
    Dim wb As Workbook
    Dim ws As Worksheet

    fPath = "C:\Users\A9900899\Desktop\bob\VBAProject\Raw\"
    StrFile = Dir(fPath)

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    While StrFile <> ""
        Debug.Print StrFile
        If StrFile Like "*xls*" Then ' check that current file is Excel type
            Set wb = Workbooks.Open(fPath & StrFile)
            For Each ws In wb.Sheets
                Debug.Print ws.Name
            Next ws
            wb.Close False ' close workbook and don't save changes
        End If
        StrFile = Dir
    Wend
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True

End Sub
Run Code Online (Sandbox Code Playgroud)