EXCEL VBA MACRO EXAMPLE

Loop Through All Sheets

Excel VBA macro example for: Loops through all sheets in the workbook. Review the generated code, explanation, steps, and safety notes.

User request

Loops through all sheets in the workbook

Generated VBA code

Option Explicit

Sub LoopThroughAllSheets()
    Dim ws As Worksheet
    Dim sheetCount As Long
    Dim i As Long
    
    ' Validate that there is at least one sheet
    If ThisWorkbook.Sheets.Count = 0 Then
        MsgBox "No sheets found in the workbook.", vbExclamation
        Exit Sub
    End If
    
    sheetCount = ThisWorkbook.Sheets.Count
    
    ' Loop through each sheet in the workbook
    For i = 1 To sheetCount
        Set ws = ThisWorkbook.Sheets(i)
        
        ' Example action: Display the sheet name in the Immediate Window
        Debug.Print "Processing sheet: " & ws.Name
        
        ' Add your custom code here to perform actions on each sheet
        ' For example, you could modify cells, format, etc.
        
    Next i
    
    MsgBox "Loop completed. Processed " & sheetCount & " sheets.", vbInformation
End Sub

What the macro does

  • The macro uses a For loop to iterate through all sheets in the active workbook.
  • It validates that there is at least one sheet to avoid errors.
  • For each sheet, it prints the sheet name to the Immediate Window (View > Immediate Window in VBA editor) as an example action.
  • You can replace the Debug.Print line with your own code to perform specific tasks on each sheet.
  • After the loop, a message box confirms completion and shows the number of sheets processed.

How to use it

  1. Press Alt+F11 to open the VBA editor.
  2. Insert a new module (Insert > Module).
  3. Copy and paste the provided code into the module.
  4. Press F5 to run the macro.
  5. Check the Immediate Window (Ctrl+G) to see the sheet names printed.
  6. Modify the code inside the loop to perform your desired actions on each sheet.

Generate your own Excel macro