There are a few ways you can use VBA code to select a worksheet. I’ll show you three ways you can achieve this.
Activate worksheet by the name
Let’s say that you have two sheets. The following code will switch from any sheet to “Sheet1”. If the sheet doesn’t exist it returns an error.
In our example, we have the “Sheet2” selected.
First, you have to open VBA Editor by pressing Alt + F11. Next, enter the following code.
1 2 3 |
Sub ActivateSheet() Worksheets("Sheet1").Activate End Sub |
or
1 2 3 |
Sub ActivateSheet() Sheets("Sheet1").Activate End Sub |
If you run the code the “Sheet1” becomes an active sheet.
Activate worksheet with index
Instead of using the worksheet’s name, I would recommend using its index. By using the following code use can achieve the same result as you had in the previous example.
1 2 3 |
Sub ActivateSheet() Sheets(1).Activate End Sub |
But you have to be careful. If you change the arrangement of sheets, the code will activate “Sheet2”.
Take a look at the following example.
If you run the code the “Sheet2” becomes now an active sheet because it’s in the first position.
Activate worksheet with index
If you have multiple worksheets and you want to activate the last one, you can use the following code.
1 2 3 |
Sub ActivateSheet() Sheets(Sheets.Count).Activate End Sub |
This is our example.
If you run the code “Sheet4”, which is the last one in the workbook, will become active.