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

时间:2017-03-30 06:50:00

标签: vba excel-vba excel

我想遍历文件夹中的所有工作簿,然后遍历每个工作簿的所有工作表。我有下面的代码,但目前问题在于行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

这里我的错误是什么?

1 个答案:

答案 0 :(得分: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