The following VBA procedure demonstrates how to activate two specific worksheets in sequence within the same workbook:
Sub ActivateSheets()
ThisWorkbook.Activate
Worksheets("Sheet3").Activate
MsgBox ActiveSheet.Name
Worksheets("Sheet1").Activate
MsgBox ActiveSheet.Name
End Sub
Explanation:
- Ensure the correct workbook is active
- Activate
This ensures that the code operates within the workbook containing the macro. This is essential when multiple workbooks are open in the Excel session.
Activate a specific worksheet
Worksheets(« Sheet3 »).Activate
MsgBox ActiveSheet.Name
-
- The Activate method is used to make « Sheet3 » the currently active sheet.
- Once activated, any subsequent operations (like writing to a cell or selecting a range) will affect this sheet.
- A message box displays the name of the newly active sheet as confirmation.
Activate another worksheet
Worksheets(« Sheet1 »).Activate
MsgBox ActiveSheet.Name
-
- The macro then switches focus to « Sheet1 » using the same method.
- Again, a message box confirms the name of the active sheet.
Why use .Activate?
Using .Activate is helpful when:
- You want to ensure that the user sees a specific worksheet.
- You plan to run commands that operate on the active sheet (like selecting ranges or pasting values).
- You’re creating a guided process that walks users through different sheets.
⚠️ Important Note:
Before running this macro, make sure that the sheets « Sheet3 » and « Sheet1 » (or « Tabelle3 » and « Tabelle1 » in the original German workbook) exist in the workbook. Otherwise, Excel will throw a runtime error.
✅ Optional: Add error handling
You can make the procedure more robust by adding a check to ensure the sheets exist before attempting to activate them:
Sub ActivateSheetsSafely()
ThisWorkbook.Activate
If SheetExists("Sheet3") Then
Worksheets("Sheet3").Activate
MsgBox ActiveSheet.Name
End If
If SheetExists("Sheet1") Then
Worksheets("Sheet1").Activate
MsgBox ActiveSheet.Name
End If
End Sub
Function SheetExists(sheetName As String) As Boolean
On Error Resume Next
SheetExists = Not Worksheets(sheetName) Is Nothing
On Error GoTo 0
End Function