This post may contain affiliate links. Please read my disclosure for more info.
Advertisement:

Loop through every worksheet or every workbook

VBA Code Snippets

webimagevbacodesnippets


Advertisement:

Looping through every worksheet or every workbook is a very common action. One which you may be doing on a regular basis.  The code below should set you on the right path.


Advertisement:

 

Loop through every worksheet

Sub LoopThroughWorksheets()

'Create a variable to hold the worksheet and also the output message
Dim Ws As Worksheet
Dim Message As String
'Loop through each worksheet in the Worksheets collection of the active workbook
For Each Ws In ActiveWorkbook.Worksheets

    'Insert the actions you wish to take on every worksheet
    'In this example adding the name of a sheet to a string
    Message = Message & Ws.Name & vbNewLine

Next Ws

'Output the string containing the name of each worksheet
MsgBox Message

End Sub

 

Loop through every workbook

Sub LoopThroughWorkbooks()

'Create a variable to hold the workbook and also the output message
Dim Wb As Workbook 
Dim Message As String

'Loop through every open workbook in the workbooks collection of the active Excel session 
For Each Wb In Workbooks

    'Insert the actions you wish to take on every workbook 
    'In this example adding the name of a sheet to a string
    Message = Message & Wb.Name & vbNewLine 

Next Wb 

    'Output the string containing the name of each workbook
MsgBox Message 

End Sub