简体   繁体   中英

Loop through workbook and sheets in each workbook vba

I want to loop through all Workbooks in a folder and then loop through all worksheets of each workbook. I have the code below but currently the problem is with the line 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

What is my mistake here?

In order to loop through all Workbook.Sheets you need to Set wb to the current StrFile , and then loop through wb.Sheets .

Using Application.ScreenUpdating = False and Application.DisplayAlerts = False will minimize all screen flickering and Excel alerts.

Code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM