Activate Workbook Or Worksheet in Excel VBA

Description:

Sometimes we may want to Activate Workbook Or Worksheet using Excel VBA.You can use Activate property Activate Workbook Or Work Sheet.

For example, we may have 5 worksheet, we have to do some tasks in Sheet3. In order to perform some tasks we need to activate the worksheet then perform the tasks.

Activate Workbook Or Work Sheet – Example Cases:

Activate Workbook or Worksheet

If you know the name of the workbook You can use the following code to Activate Workbook or worksheet. For example workbook name is “Book2″ which we want to activate and it contains sheet named as “Sheet1″. Using following code you can Activate Workbook Or Work Sheet.

Code:

[code language="vb"]

Sub Activate_Workbook()

'Activate Workbook
Workbooks("Book2.xls").Activate

'Activate Worksheet
Workbooks("Book2.xls").Sheets("Sheet1").Activate

End Sub

[/code]

Output:

Activate Workbook Or Work Sheet

Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. Insert a new module from Insert menu
  4. Copy the above code and Paste in the code window
  5. Press F5 to see the output
  6. You should see Aactivated workbook and Worksheet
  7. Save the file as macro enabled workbook
Activate Workbook or Worksheet using object

You can create object for workbook and worksheet in the following way.You can use object to activate Workbook or Worksheet.

Code:

[code language="vb"]

Sub Activate_Workbook_Using_Object()

'Variable Declaration
Dim WrkBk As Workbook
Dim WrkSht As Worksheet

'Create Object for Workbook
Set WrkBk = Workbooks.Add

'Create Object for Worksheet
Set WrkSht = WrkBk.Sheets("Sheet1")

'Activate Sheet
WrkSht.Activate

End Sub

[/code]

Explanation:
  1. We declared two objects for workbook and worksheet
  2. We have added a new workbook and assigned to workbook object
  3. We set the Worksheet to worksheet object
  4. We activated the worksheet by refering the worksheet object
  5. .

Instructions:
  1. Open an excel workbook
  2. Press Alt+F11 to open VBA Editor
  3. Insert a new module from Insert menu
  4. Copy the above code and Paste in the code window
  5. Press F5 to see the output
  6. You should see output as shown above
  7. Save the file as macro enabled workbook

Valli

Excel VBA Developer having around 8 years of experience in using Excel and VBA for automating the daily tasks, reports generation and dashboards preparation. Valli is sharing to helps us automating daily tasks.

You may also like...

1 Response

  1. Jude says:

    Hi,
    If you worksheet has a space in its name eg: ‘Sheet 1′, how would you reference that?
    (Workbooks(“Book2.xls”).Sheets(“Sheet1″).Activate)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>