Vba for excel activesheet

Skip to content

VBA ActiveSheet – Excel Active Sheet Object

  • ActiveSheet VBA in Excel

VBA ActiveSheet Object helps to refer the currently activated sheet in the active workbook. We can get all properties and methods of the ActiveSheet using VBA. Let us see the useful of the examples on Excel VBA ActiveSheet Object.

What is Active Sheet in Excel VBA?

Worksheet which is currently activated in the Active Workbook and Active Window is referred as Active Sheet. You can make any Worksheet as Active Worksheet by Activating a Worksheet. You can use Activate Method of Worksheet to activate a sheet using Excel VBA.

Sheets("SheetName").Activate

Set a Worksheet as Active Sheet in VBA

You can use Activate method to set worksheet as active sheet in VBA. For example, you can set the Sheet 3 as active sheet by calling the Activate Method.

Sheets(3).Activate

Reading the Data from ActiveSheet

We can use the VBA to read the data from ActiveSheet Object. We can use all the methods and properties of a worksheet Object. For example, the following example get the data from ActiveSheet and show it in a message box.

Sub sbGetDataFromActiveSheet()
MsgBox ActiveSheet.Range("D5")
End Sub

The code statement ActiveSheet.Range(“D5”) is reading the data from Range D5 of ActiveSheet. It is not mandatory to specify the ActiveSheet befor Range object in the above macro. Range(“D5”) also refer the data from ActiveSheet.

Then, when do we use ActiveSheet Object in Real-time projects?

Uses of ActiveSheet in VBA Development

We deal with multiple worksheets while automating an Excel Task. We can simply set the ActiveSheet to a variable and keep it fro future reference.

For example: Let us say, we have 3 worksheets in the Workbook and currently you have activated Sheet 2 and You wants to move into Sheet 3 and refer the Sheet2 Data. You can use the ActiveSheet Object in this scenario.

Sub sbGetDataFromActiveSheet()
'You wants to work on Sheet 2
Sheets(2).Activate
'Reading the Data from ActiveSheet Range A1
K = Range("A1")

'Now you wants to move into Sheet 3.
'Let us set the ActiveSheet into a temporary variable before activating the sheet 3
Set sht = ActiveSheet

'Now activate Sheet 3
Sheets(3).Activate

'Enter Data from Range D3 of Sheet 2 in Range A1 of Sheet 3
Range("A1") = sht.Range("D3")
End Sub

Get the Name of the ActiveSheet

You can use the .Name property of the ActiveSheet object to return the ActiveSheet Name using VBA.

Sub sbActiveSheetName()
MsgBox ActiveSheet.Name
End Sub

Copy the Data from Other Sheet and Paste in the ActiveSheet

We can copy the data from a worksheet (it can be the same sheet or a different sheet)  and paste in the ActiveSheet.

Sub sbCopyFromOtherSheetAndPasteInActiveSheet()
Sheets(2).Activate
Sheets(3).Range("A1:G25").Copy
Range("G1").Select
Activeheet.Paste
End Sub

The above macro will Activate the Sheet 2. And copy the data from Sheet 3 and Paste at Range G1 of the ActiveSheet.

Count Shapes in ActiveSheet

The following macro will return the number of shapes in ActiveSheet.

Sub sbCountShepsInActiveSheet()
MsgBox Activeheet.Shapes.Count
End Sub

Count Charts in ActiveSheet

The following macro will return the number of Chart Objects in ActiveSheet.

Sub sbCountChartsInActiveSheet()
MsgBox Activeheet.ChartObjects.Count
End Sub

Protect in ActiveSheet using VBA

You can use the Protect Method of ActiveSheet to password protect the Sheet.

Sub sbProtectSheet()
    ActiveSheet.Protect "password", True, True
End Sub

UnProtect: You can use unprotect method of Activesheet to unprotect the sheet.

    ActiveSheet.UnProtect "password"
Effortlessly Manage Your Projects and Resources
120+ Professional Project Management Templates!

A Powerful & Multi-purpose Templates for project management. Now seamlessly manage your projects, tasks, meetings, presentations, teams, customers, stakeholders and time. This page describes all the amazing new features and options that come with our premium templates.

Save Up to 85% LIMITED TIME OFFER
Excel VBA Project Management Templates
All-in-One Pack
120+ Project Management Templates
Essential Pack
50+ Project Management Templates

Excel Pack
50+ Excel PM Templates

PowerPoint Pack
50+ Excel PM Templates

MS Word Pack
25+ Word PM Templates

Ultimate Project Management Template

Ultimate Resource Management Template

Project Portfolio Management Templates

Related Posts

    • What is Active Sheet in Excel VBA?
    • Set a Worksheet as Active Sheet in VBA
    • Reading the Data from ActiveSheet
    • Uses of ActiveSheet in VBA Development
    • Get the Name of the ActiveSheet
    • Copy the Data from Other Sheet and Paste in the ActiveSheet
    • Count Shapes in ActiveSheet
      • Count Charts in ActiveSheet
    • Protect in ActiveSheet using VBA

VBA Reference

Effortlessly
Manage Your Projects

120+ Project Management Templates

Seamlessly manage your projects with our powerful & multi-purpose templates for project management.

120+ PM Templates Includes:

Effectively Manage Your
Projects and  Resources

With Our Professional and Premium Project Management Templates!

ANALYSISTABS.COM provides free and premium project management tools, templates and dashboards for effectively managing the projects and analyzing the data.

We’re a crew of professionals expertise in Excel VBA, Business Analysis, Project Management. We’re Sharing our map to Project success with innovative tools, templates, tutorials and tips.

Project Management
Excel VBA

Download Free Excel 2007, 2010, 2013 Add-in for Creating Innovative Dashboards, Tools for Data Mining, Analysis, Visualization. Learn VBA for MS Excel, Word, PowerPoint, Access, Outlook to develop applications for retail, insurance, banking, finance, telecom, healthcare domains.

Analysistabs Logo

Page load link

VBA Projects With Source Code

3 Realtime VBA Projects
with Source Code!

Take Your Projects To The Next Level By Exploring Our Professional Projects

Go to Top

Return to VBA Code Examples

In this Article

  • ActiveSheet
    • Activate Worksheet (Setting the ActiveSheet)
    • ActiveSheet Name
  • Selected Sheets vs ActiveSheet
  • Select Worksheet
    • Select Worksheet by Tab Name
    • Select Worksheet by Index Number
    • Select Worksheet With VBA Code Name
    • Select Current Worksheet
  • More Activate / Select Sheet Examples
    • Set ActiveSheet to Variable
    • Change ActiveSheet Name
    • With ActiveSheet
    • Loop Through Selected Sheets
    • GoTo Next Sheet
  • VBA Coding Made Easy

This article will discuss the ActiveSheet object in VBA. It will also discuss how to activate, select, and go to Worksheets (& much more). Read our full VBA Worksheets Guide for more information about working with worksheets in VBA.

ActiveSheet

In VBA, ActiveSheet refers to the currently active Worksheet. Only one Sheet may be active at a time.

Activate Worksheet (Setting the ActiveSheet)

To set the ActiveSheet use Worksheet.Activate:

Worksheets("Input").Activate

The Activate Sheet command will actually “go to” the sheet, changing the visible Sheet.

vba activate sheet

The above example uses the Sheet (Tab) name.  Instead you can use the VBA code name for the worksheet:

Sheet1.Activate

vba activesheet

ActiveSheet Name

To get the ActiveSheet Name:

msgbox ActiveSheet.name

Selected Sheets vs ActiveSheet

At any point in time, only one Sheet can be the ActiveSheet. However, multiple Worksheets can be selected at once.

When multiple Worksheets are selected only the “top-most” Worksheet is considered active (the ActiveSheet).

vba selected sheets

Select Worksheet

If you would like to select a worksheet instead of activating it. Use .Select instead.

Select Worksheet by Tab Name

This selects a Worksheet based on it’s Sheet Tab Name

Sheets("Input").Select

vba select sheet

Select Worksheet by Index Number

This selects a Worksheet based on it’s position relative to other tabs

Worksheets(1).Select

vba select sheet index number

Select Worksheet With VBA Code Name

Sheet1.Select

Selecting worksheets by code name can prevent errors caused by worksheet name changes.

Select Current Worksheet

To select the current Worksheet, use the ActiveSheet object:

ActiveSheet.Select

More Activate / Select Sheet Examples

VBA Programming | Code Generator does work for you!

Set ActiveSheet to Variable

This will assign the ActiveSheet to a Worksheet Object Variable.

Dim ws As Worksheet

Set ws = ActiveSheet

Change ActiveSheet Name

This will change the ActiveSheet Name.

ActiveSheet.Name = "NewName"

With ActiveSheet

Using the With Statement allows you to streamline your code when working with objects (such as Sheets or ActiveSheet).

With ActiveSheet
    .Name = "StartFresh"
    .Cells.Clear
    .Range("A1").Value = .Name
End With

Notice how you don’t need to repeat “ActiveSheet” before each line of code. This can be a huge time saver when working with a long list of commands.

Loop Through Selected Sheets

The following macro will Loop through all selected sheets, displaying their names.

Sub GetSelectedSheetsName()
    Dim ws As Worksheet

    For Each ws In ActiveWindow.SelectedSheets
         MsgBox ws.Name
    Next ws

End Sub

GoTo Next Sheet

This code will go to the next Sheet. If the ActiveSheet is the last Sheet, then it will go to the first Sheet in the Workbook.

If ActiveSheet.Index = Worksheets.Count Then
    Worksheets(1).Activate
Else
    ActiveSheet.Next.Activate
End If

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

Select Activate Worksheet

Learn More!

<<Return to VBA Examples

What is VBA Activesheet Property?

The active sheet means the current worksheet which you are
working on and viewing. The ActiveSheet object signifies the worksheet tab that
is selected before running the VBA code. If the user is working with multiple
sheets, then the currently viewed files are considered as the active sheet. VBA
facilitates many properties and methods that can be called using the
ActiveSheet object.

By Default, Excel considered the only topmost worksheet as
the ActiveSheet, and all the VBA coding is applicable only for the topmost
worksheet. The user can mark or align any Excel worksheet as the Active sheet
by calling the Activesheet object with the sheet name. One can also use the VBA
Activate method to activate any Excel sheet.

People often confuse the Active worksheet with the selected
sheet and use them interchangeably. But both have different
functionalities.  Let’s evaluate the
difference below:

Selected Worksheet  Active Worksheet
Selected Worksheet can select one or more Excel Worksheets
within an Excel Window.
 
Active Worksheet only selects the current Worksheet to view and work
upon.
 
Each Workbook can have multiple Selected Worksheets At a time, only one active sheet can be selected.

Importance of Using ActiveSheet Object

  1. This property is useful when a user wants to use
    another sheet (to run the VBA code and modify the objects apart from the
    topmost worksheet.
  2. Many times we automate an Excel task with the
    help of multiple worksheets. In this situation, we can use Activesheet property
    to set the Activesheet variable and practice it for future reference.

Syntax

expression.ActiveSheet

where the expression variable
represents an application object.

Return

This property returns a sheet object representing the active
sheet in the current Excel Workbook. It returns null if the worksheet has no active
sheet.

Read Data from ActiveSheet

One of the basic tasks in VBA’s day to day life is to read
data from Excel ActiveSheet. The worksheet’s range object can be used to read
data from the ActiveSheet Object.

Although, if you are referring to the topmost sheet,
then it’s not necessary to specify ActiveSheet function before Range
object.  In the below code Range (“B5”)
can also read the data from ActiveSheet.

Code:

Sub ActiveSheet_ReadProperty()
 'reading the value of B5 cell in the ActiveSheet
 'with the help of Range object
 MsgBox ActiveSheet.Range("B5")
 'if ActiveCell object is not specified
 MsgBox Range("B5") 'it will return the same value as above
 End Sub 

Let’s work with the set-by-step code of lines:

Step 1: Open the VBA developer tab either by using
the shortcut keywords Alt +F11 or click on developer window -> visual basic
editor.

Step 2: Visual Basic Editor will open. Next step is
to create a module. Right-clicking on the VBA Project-> Click on Insert->
Click on Module.

VBA ActiveSheet

Step 3: In the Module window, introduce the sub-block,
followed by your macro name.

VBA ActiveSheet

Step 4: We will call the ActiveSheet function and to read
the data will specify the Range object (specifying the cell or range in it.

VBA ActiveSheet

Step 5: With the help of ‘Msgbox’ will display the output.

VBA ActiveSheet

Step 6: We will repeat the above 2 steps, but this time
will not specify the ActiveSheet object.

VBA ActiveSheet

Output

Step 7: Execute the above code either by pressing the F5
shortcut key or by clicking on the Run button.

Step 8: You will notice that the output has been displayed in
the message box.

VBA ActiveSheet

Step 9: Press OK. Again, the message box dialog will be
displayed, and both the outputs will be the same.

VBA ActiveSheet

ActiveSheet Name

The VBA  ‘.Name
‘property of the ActiveSheet fetches the name of your sheet. With the help of
the name, you can proceed with many applications.

Code:

Sub ActiveSheet_NameProperty()
 'fetching the name of the ActiveSheet with help of
 'ActiveSheet.Name property
 MsgBox "The name of ActiveSheet is" & ActiveSheet.Name
 End Sub 

Let’s work with the set-by-step code of lines:

Step 1: Open the VBA developer tab either by using
the shortcut keywords Alt +F11 or click on developer window -> visual basic
editor.

Step 2: Visual Basic Editor will open. Next step is
to create a module. Right-clicking on the VBA Project-> Click on Insert->
Click on Module.

VBA ActiveSheet

Step 3: In the Module window, introduce the sub-block,
followed by your macro name.

VBA ActiveSheet

Step 4: With the help of MsgBox, we will display the
name by using VBA ActiveSheet.Name property.

VBA ActiveSheet

Output

Step 5: Execute the above code either by pressing the
F5 shortcut key or by clicking on the Run button.

Step 6: You will notice that the name has been
displayed in the MsgBox.

VBA ActiveSheet

Password Protection in ActiveSheet

You can secure your ActiveSheet from unintended users and
safeguard your data by using the VBA protect method. It will set a password in
your current sheet. If needed, you can even remove it by using the VBA
UnProtect method.

Syntax

  1. Protect Data
ActiveSheet.Protect ([Password], [DrawingObjects], …)
  • UnProtectData
ActiveSheet.UnProtect “password”

Code:

Sub ActiveSheet_ProtectProperty()
 'protect method is used to secure the
 'ActiveSheet with password
 ActiveSheet.Protect "password", True, True
 End Sub 

Let’s work with the set-by-step code of lines:

Step 1: Open the VBA developer tab either by using
the shortcut keywords Alt +F11 or click on developer window -> visual basic
editor.

Step 2: Visual Basic Editor will open. Next step is
to create a module. Right-clicking on the VBA Project-> Click on Insert->
Click on Module.

VBA ActiveSheet

Step 3: Protect your Excel sheet with the help of
ActiveSheet.Protect method.

VBA ActiveSheet

Output

Step 4: Run the output by clicking the F5 function
key.

Step 5: you will notice you can no more write
anything in the sheet. An alert dialogue box will pop up stating “The cell or
chart you’re trying to change in on a protected sheet. To make a change,
unprotect the sheet. You might be requested to enter a password”

VBA ActiveSheet

To Unprotect the Sheet

To again access/ write or format the sheet you must
unprotect the sheet. To unprotect the Excel sheet, use the ActiveSheet. Unprotect
method.

Code:

Sub ActiveSheet_UnProtectProperty()
 'protect method is used to secure the
 'ActiveSheet with password
 ActiveSheet.Protect "password", True, True
 'unprotecting the sheet
 ActiveSheet.Unprotect "password"
 End Sub 

Now your sheet has been unprotected.

ActiveSheet Clear Method

The ActiveSheet.Clear method is used to clear off all the
content of the cells in the active cells.

Code:

Sub ActiveSheet_ClearProperty()
 'to clear the content of all the cells
 'in the Activesheet with the help of Clear method
 ActiveSheet.Cells.Clear
 End Sub 

VBA ActiveSheet

Output

Before the Clear method

VBA ActiveSheet

After the Clear method: All the content would be erased.

VBA ActiveSheet

Activate another sheet as ActiveSheet

We can active any random sheet as an ActiveSheet. For this,
the ‘.Activate’ method is used.

Code:

Sub ActiveSheet_ActivateSheet()
 'activating Sheet2
 Sheet2.Activate
 'inserting value in cell B2
 ActiveSheet.Cells(2, 2) = "Hello ActiveSheet"
 End Sub 

VBA ActiveSheet

Output

You will notice that in Sheet2, at cell address B2, “Hello
ActiveSheet” value has been entered.

VBA ActiveSheet

In this post, you’ll be learning how you can select a worksheet and activate it using Excel VBA.

ActiveSheet in Excel

The term ActiveSheet, refers to the currently active Worksheet in Excel VBA.

Let’s see in detail about the active sheet command.

To run the code,

  • Under the developer tab, click visual basic

  • Click the insert option and choose module
  • Enter your code and click run.

How to Activate or Set the WorkSheet in Excel VBA?

To set the ActiveSheet use Worksheet.Activate:

Worksheets("Sheetname").Activate

This sheet will activate a new worksheet in the current workbook.

If you want to activate an existing sheet,

ActiveSheet Name

To get the ActiveSheet Name, use the property ActiveSheet.name in Excel VBA.

ActiveSheet Name

Selected Sheets vs ActiveSheet in Excel VBA

At any point in time, only one Sheet can be the ActiveSheet in Excel VBA.But, multiple Worksheets can be selected at once.

If multiple Worksheets are selected, then the Worksheet with top most priority is considered as active sheet.

Select Worksheet

If you want to select a worksheet instead of activating it you can use .select  in the above codes instead of activate command.

Select Worksheet by Tab Name

This code line selects a Worksheet based on its Sheet Tab Name

Sheets("Select sheet).Select

Select Worksheet by Index Number

This code line selects a Worksheet based on its position relative to other tabs

Select Worksheet with VBA Code Name

To select worksheet using VBA code name, enter the following code

Selecting worksheets by code name will prevent errors.

Select Current Worksheet

To select the current Worksheet, you can use the ActiveSheet object:

Change ActiveSheet Name

To change the active sheet name

ActiveSheet.Name = "New active sheet"

GoTo Next Sheet

To go to next sheet, enter the following code. If the active sheet is the last sheet, this command will go to the first sheet.

If ActiveSheet.Index = Worksheets.Count Then

    Worksheets(1).Activate

Else

    ActiveSheet.Next.Activate

End If

Today we are going to learn about VBA Worksheets. We will cover all the nuisances e.g. VBA Activesheet and how it compares to regular Worksheets, how to Select Worksheets, how to Activate Worksheets, Selecting vs Activating Worksheets… and everything else you need to know about the VBA Worksheet in general.

ThisWorkbook vs ActiveWorkbook

Some Excel Worksheets Some Excel WorksheetsLets start with the basics. Before we start I want to stress and remind the difference between ActiveWorkbooks and ThisWorksbooks. In short:

  • ThisWorkbook – refers to the Workbook in which the VBA macro is running
  • ActiveWorkbook – refers to the Workbook which is in the topmost Excel Window

It is extra important to understand this difference and I encourage you to read my post on this topic first.

The Excel VBA Object Hierarchy

Excel vba object hierarchySecondly it makes sense to remind the Excel Object hierarchy.

At the top, at the root we have our Excel Application. The Excel Application represents the entire Excel process. Further down the tree we have our Workbooks. Each Application contains a collection of Workbooks. Looking into a single Workbook we will notice it contains a collection of Worksheets. Worksheets on the other hand as you know can define Ranges (not the same a single cells). Using a Range we can access its cells Values or Formulas.

Accessing VBA Worksheets

Now that we have that behind us lets explore the different ways in which we can access Worksheets in VBA:

ActiveWorkbook VBA Worksheets

The Sheets and Worksheets collections

Sheets within the ActiveWorkbook:

Dim ws as Worksheet, wsCollection as Sheets
Set wsCollection = Sheets 'Get entire collection of Worksheets
Set ws = Sheets(1) 'Get first Worksheet in ActiveWorkbook
Set ws = Sheets("Sheet1") 'Get Worksheet named "Sheet1" in ActiveWorkbook

Similarly we can use Worksheets instead of Sheets.

Dim ws as Worksheet, wsCollection as Sheets
Set wsCollection = Worksheets 'Get entire collection of Worksheets
Set ws = Worksheets(1) 'Get first Worksheet in ActiveWorkbook
Set ws = Worksheets("Sheet1") 'Get Worksheet named "Sheet1" in ActiveWorkbook

ThisWorkbook VBA Worksheets

The Sheets and Worksheets collections

Sheets within the ThisWorkbook:

Dim ws as Worksheet, wsCollection as Sheets
Set wsCollection = Sheets 'Get entire collection of Worksheets
Set ws = ThisWorkbook.Sheets(1) 'Get first Worksheet in ThisWorkbook
Set ws = ThisWorkbook.Sheets("Sheet1") 'Get Worksheet named "Sheet1" in ThisWorkbook

Similarly we can use Worksheets instead of Sheets.

Dim ws as Worksheet, wsCollection as Sheets
Set wsCollection = Worksheets 'Get entire collection of Worksheets
Set ws = ThisWorkbook.Worksheets(1) 'Get first Worksheet in ActiveWorkbook
Set ws = ThisWorkbook.Worksheets("Sheet1") 'Get Worksheet named "Sheet1" in ThisWorkbook

Worksheet VBA Name vs Excel Name

Worksheet VBA Name vs Excel Name When speaking about Worksheets in ThisWorkbook, the VBA Name of a Worksheet is not the same as the Excel Name of a Worksheet. Let us understand this different. On the right we have a screen from an example Workbook. The VBAName string is the VBA Name of our Worksheet, on the other hand the Excel Name string is our Excel Name. You can use both names to refer to the same Worksheet but in different ways.

Using the VBA Name of a Worksheet

Worksheet VBA Name Worksheet VBA NameWe can refer to a VBA Worksheet by its VBA Name directly – just by typing it. This is very convenient and a good practice. That is because the VBA Name can’t be changed by a user by mistake from the level of Excel (not the VBE). Hence whatever name the user give from the Workbook level to your Worksheet – its VBA Name stays the same.

Using the Excel Name of a Worksheet

Referring to an Excel Worksheet from VBA is not a recommended practice. Below I am referring to the Worksheet I named Excel Name in my example above.

Dim ws as Worksheet

Set ws = Worksheets("Excel Name") 'Get Worksheet named "Sheet1" in ActiveWorkbook

Not what you notice is that compared to acquiring the Worksheet by its VBA Name, when using the defaults Worksheets or Sheets object you land with the said Worsheet, but from the ActiveWorkbook. Usually this doesn’t do much of a difference. But I am highlighting that this is simply another place to make a common mistake. See both versions below:

Dim ws as Worksheet

'---Sheet by Excel Name in ActiveWorkbook---
Set ws = Worksheets("Excel Name") 'Get Worksheet named "Sheet1" in ActiveWorkbook
Set ws = ActiveWorkbook.Worksheets("Excel Name") 'Get Worksheet named "Sheet1" in ActiveWorkbook

'---Sheet by Excel Name in ThisWorkbook---
Set ws = ThisWorkbook.Worksheets("Excel Name") 'Get Worksheet named "Sheet1" in ActiveWorkbook

As with Active vs ThisWorkbook you need to first understand the difference between Selecting a Worksheet and Activating it.

Selected vs Activated Worksheet, the differences:

  • Selected Worksheet – one or more Worksheets that have been selected within an Excel Window. Each Workbook has its own set of Selected Worksheets
  • ActiveWorksheet – the current Worksheet you are viewing and working in. The only top-most Worksheet in all Application Workbooks

From the definition above you see that there can be more than 1 Selected Worksheet, while only 1 ActiveSheet. In fact both are totally different things. Lets explore this in some examples:

Example 1: Explaining ActiveSheet

vba worksheets exampleLet us say we have 2 Workbooks open. One is Book1.xlsm and there other is Book2.xlsm.

Lets open VBE in Book1.xlsm. We will add the following piece of code:

Sub TestActiveSheet()
 MsgBox ActiveSheet.Name
End Sub

Now lets activate Book2.xlsm. Rename any Worksheet e.g. to MyActiveWorksheet. Next go to the Developer ribbon select Macros and run Books1.xlsm!TestActiveSheet. What happened? You probably got something like this:
vba activesheet
Although you ran a macro from Book1.xlsm, VBA considers always the top-most worksheet as the ActiveSheet.

Example 2: Explaining Selected vs ActiveSheet

Let us consider the same example. Open Book1.xlsm and add the following code to the VBE:

Sub SelectedVSActive()
  Dim res As String, ws As Worksheet
  res = "Selected sheets:" & vbNewLine
  For Each ws In ActiveWindow.SelectedSheets
    res = res & ws.Name & vbNewLine
  Next ws
  MsgBox res & vbNewLine & "ActiveSheet:" & vbNewLine & ActiveSheet.Name
End Sub

Now do the following:

  • Activate workbook Book2.xlsm
  • Select a number of Worksheets (at least 2)
  • Run Book1.xlsm!SelectedVSActive macro

What happens? You should get something like this:
vba activesheet vs selected
You see that:

  • Only the top-most Worksheet is considered as the ActiveSheet
  • The ActiveSheet is ALWAYS considered as a Selected Worksheet within the ActiveWindow (this last part is important)

What happens if you change ActiveWindow to e.g. Windows(2)? You will see a different set of Selected Worksheets. Why? Because all Workbooks have Selected Worksheets. Hope you see the difference.

Activating VBA Worksheets

Activating Worksheet is easy in VBA. You do it using the Activate property of Worksheets. How to activate any Worksheet using VBA?

Dim ws as Worksheet
'...Set ws to some Worksheet
ws.Activate

Activate Worksheet examples

A few examples below:

Sheets(1).Activate 'Activate first Worksheet in ActiveWorkbook
Sheet1.Activate 'Activate Sheet1 in ThisWorkbook
Worksheets("MyNamedWorksheet").Activate 'Activate Excel named Worksheet in ActiveWorkbook

Selecting VBA Worksheets

Selecting Worksheets is a little more difficult as we may want to select a single Worksheet or more.

Selecting a single VBA Worksheet

Selecting a single VBA Worksheet is simple. Just use the Select property of a Worksheet.

Dim ws as Worksheet
'...Set ws to some Worksheet
ws.Select

Selecting a single Worksheet examples

A few examples below:

Sheets(1).Select 'Select first Worksheet in ActiveWorkbook
Sheet1.Select 'Select Sheet1 in ThisWorkbook
Worksheets("MyNamedWorksheet").Select 'Select Excel named Worksheet in ActiveWorkbook

Selecting multiple VBA Worksheets

Selecting more than 1 Worksheet is a little more complex as we need to leverage the VBA Array function:

Sheets(Array(1, 2)).Select 'Select first and second Worksheet in ActiveWorkbook
Sheets(Array("Named1", "Named2")).Select 'Select 2 named Worksheets in ActiveWorkbook

This is not the most elegant way of doing it. Fortunately the Select function has an argument called Replace. Setting it to false will mean that the previously selected is not to be deselected. Thus we can extend our selections like this:

Sheets(1).Select 
Call Sheets(2).Select(False)
Call Sheets(3).Select(False)

This will select the first three Worksheets in our ActiveWorkbook.

Deleting VBA Worksheets

To delete a VBA Worksheet we need to turn off the Application.DisplayAlerts

Application.DisplayAlerts = False
Sheets(1).Delete
Application.DisplayAlerts = True

You can delete multiple Worksheets in a similar fashion as how you can do a multiple Worksheet Select:

Application.DisplayAlerts = False
Sheets(Array(1, 2)).Delete
Application.DisplayAlerts = True

Copying VBA Worksheets

You can copy Worksheets within a Workbook or from other open Workbooks.

'Copy Sheet1 and paste before Sheet2
Worksheets("Sheet1").Copy Before:=Sheets("Sheet2")

'Copy Sheet1 and paste before Sheet2 in Workbook Book1.xlsm
Worksheets("Sheet1").Copy Before:=Workbooks("Book1.xlsm").Sheets("Sheet2")

Moving VBA Worksheets

You can move Worksheets within a Workbook or from other open Workbooks.

'Move Sheet1 and paste before Sheet2
Worksheets("Sheet1").Move Before:=Sheets("Sheet2")

'Move Sheet1 and paste before Sheet2 in Workbook Book1.xlsm
Worksheets("Sheet1").Move Before:=Workbooks("Book1.xlsm").Sheets("Sheet2")

Other VBA Worksheets properties

Below are other VBA Worksheet properties worth mentioning:

Worksheet propertyDescriptionExampleCalculateCalculates all dirty formulas on the current Worksheet

Dim ws as Worksheet
'...Set ws
ws.Calculate

NameGet or set the Excel Name of the Worksheet

Dim ws as Worksheet
'...Set ws
Debug.Print ws.Name 'Print Excel Name of Worksheet
ws.Name = "New name" 'Set new name for Worksheet

Visible

Display, Hide or make Worksheet VeryHidden. Possible values:

  • xlSheetVisible
  • xlSheetVeryHidden
  • xlSheetHidden
Dim ws as Worksheet
'...Set ws
ws.Visible = xlSheetHidden 'Make ws Worksheet Hidden

To learn more read Unhide sheets in Excel / Unhide all Sheets in Excel using VBA.

Понравилась статья? Поделить с друзьями:
  • Vba for excel 2010 pdf
  • Vba for excel 2003
  • Vba for countif in excel
  • Vba for copy and paste in excel
  • Vba for checkboxes in excel