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 SubWhat 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
- Press Alt+F11 to open the VBA editor.
- Insert a new module (Insert > Module).
- Copy and paste the provided code into the module.
- Press F5 to run the macro.
- Check the Immediate Window (Ctrl+G) to see the sheet names printed.
- Modify the code inside the loop to perform your desired actions on each sheet.