How to loop through sheets with names that start with a specific letter using VBA?

To loop through sheets with names that start with a specific letter in Excel using VBA, you can write a VBA macro that iterates through each worksheet in the workbook, checks if the sheet name starts with a specified letter, and performs actions on those sheets. Here’s a step-by-step guide and example code to achieve this:

Sub LoopThroughSheetsStartingWith()
    Dim ws As Worksheet
    Dim startLetter As String
    startLetter = "A" ' Change this to the desired starting letter

    ' Loop through each worksheet in the active workbook
    For Each ws In ThisWorkbook.Worksheets
        ' Check if the worksheet name starts with the specified letter
        If UCase(Left(ws.Name, 1)) = UCase(startLetter) Then
            ' Perform desired actions on the worksheet
            ' Example: Display the worksheet name in the Immediate Window
            Debug.Print ws.Name
        End If
    Next ws
End Sub
  • Open the Visual Basic for Applications (VBA) Editor:
    • Press `ALT` + `F11` to open the VBA editor.
  • Insert a Module:
    • Right-click on any of the objects for your workbook in the Project Explorer.
    • Select `Insert` -> `Module` from the context menu.
  • Write the VBA Code:
    • Copy and paste the following VBA code into the module window.
  • Customize the Code:
    • Change the `startLetter` variable to the letter you want to check for. For example, if you want to loop through sheets whose names start with “B”, change `startLetter = “A”` to `startLetter = “B”`.
  • Run the Macro:
    • Press `F5` to run the macro or go back to Excel, click on `Developer` > `Macros`, select `LoopThroughSheetsStartingWith`, and click `Run`.
  • Perform Actions:
    • Within the `If` block, you can add any actions you want to perform on the sheets that meet the criteria. The provided example code prints the sheet names to the Immediate Window (View > Immediate Window if it’s not visible).

By following these steps and using the code provided, you can loop through sheets in your Excel workbook that have names starting with a specified letter and perform any necessary operations on them.

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project