How To Make A Worksheet Active In Excel Vba

To make a worksheet active in Excel VBA, you can use the Activate method of the Worksheet object. Here’s an example:


    Sub ActivateWorksheet()
      Dim ws As Worksheet
      Set ws = ThisWorkbook.Worksheets("Sheet1")
      
      ws.Activate
      
      ' Rest of your code here...
    End Sub
  

In this example, we declare a variable “ws” as a Worksheet object and set it to refer to the worksheet named “Sheet1” in the workbook. Then, we use the Activate method to make that worksheet active.

Once the worksheet is active, you can perform various operations on it, such as reading or modifying its cells, applying formatting, etc.

Here’s another example that demonstrates how to activate a worksheet based on its index:


    Sub ActivateWorksheetByIndex()
      Dim wsIndex As Integer
      wsIndex = 2  ' Activate the second worksheet
      
      ThisWorkbook.Worksheets(wsIndex).Activate
      
      ' Rest of your code here...
    End Sub
  

In this example, we specify the index of the worksheet we want to activate (2 in this case), and then use it to reference the worksheet using the Worksheets collection. Again, the Activate method is used to make the worksheet active.

Remember to replace “Sheet1” or the index number with the actual name or index of the worksheet you want to activate in your own code.

Similar post

Leave a comment