Set excel sheet active

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

Содержание

  1. Declare and Set Worksheet
  2. Using the ActiveSheet method to Set a variable
  3. Set a variable to a Worksheet in a Sheets collection in a specified workbook
  4. Set Worksheet in a specified workbook — by name
  5. Using the Parent Worksheet of a Range
  6. Previous and Next Worksheet
  7. VBA ActiveSheet – Excel Active Sheet Object
  8. VBA Reference
  9. 120+ Project Management Templates
  10. What is Active Sheet in Excel VBA?
  11. Set a Worksheet as Active Sheet in VBA
  12. Reading the Data from ActiveSheet
  13. Uses of ActiveSheet in VBA Development
  14. Get the Name of the ActiveSheet
  15. Copy the Data from Other Sheet and Paste in the ActiveSheet
  16. Count Shapes in ActiveSheet
  17. Count Charts in ActiveSheet
  18. Protect in ActiveSheet using VBA
  19. VBA Activate Worksheet in Excel
  20. VBA Reference
  21. 120+ Project Management Templates
  22. When we need to use Activate Worksheet method in VBA?
  23. VBA Activate Worksheet Method- Syntax
  24. VBA Activate Worksheet – with Name: Example 1
  25. VBA Activate Worksheet Method– with Number: Example 2
  26. VBA ActiveSheet Object
  27. Set ActiveSheet in Excel VBA
  28. VBA Activate Worksheet Method- Best Approach
  29. VBA Activate Worksheet Method- Instructions
  30. VBA Select Sheet, Activate Sheet, and Get Activesheet
  31. ActiveSheet
  32. Activate Worksheet (Setting the ActiveSheet)
  33. ActiveSheet Name
  34. Selected Sheets vs ActiveSheet
  35. Select Worksheet
  36. Select Worksheet by Tab Name
  37. Select Worksheet by Index Number
  38. Select Worksheet With VBA Code Name
  39. Select Current Worksheet
  40. More Activate / Select Sheet Examples
  41. Set ActiveSheet to Variable
  42. Change ActiveSheet Name
  43. With ActiveSheet
  44. Loop Through Selected Sheets
  45. GoTo Next Sheet
  46. VBA Coding Made Easy
  47. VBA Code Examples Add-in

Declare and Set Worksheet

To be able to operate on a worksheet using VBA you have to specify which worksheet. Below discusses the many ways you can do this. If you use the Code VBA add-in using Set will add the declaration automatically. The below sections give an overview of the ways to Set a Worksheet variable from the available ones (see also Setting a Worksheet you just added.) In the code examples in the next sections the name of the worksheet variable is kept simple to ‘ws’ and its declaration is ignored:

Tip
Shift-SPACE after the = in a Set statement opens the Set menu for the type, allowing you to select the appropriate statement (assuming Code VBA is installed)

Using the ActiveSheet method to Set a variable

The method ActiveSheet gives you direct access to the currently active worksheet. This sheet is the most likely one when working from a macro on a button on a Worksheet, or when you are writing a general purpose add-in. In such a case however there is little reason to add an extra worksheet variable, working from ActiveSheet directly is more direct. the default use is Application.ActiveSheet , alternatives are ActiveWindow.ActiveSheet and

Set a variable to a Worksheet in a Sheets collection in a specified workbook

Often, you will want to Set a variable to a Worksheet in a Worksheets or Sheets collection of a Workbook. The submenu from Sheets lets you get the code

Set Worksheet in a specified workbook — by name

If you write macros for a specific line of business, your worksheet actions will generally assume a specific (type of) workbook as it’s context. As an example, below code could be included in an Excel file with a worksheet called Locations. If your macro would involve more worksheets, you would probably name the variable wsLocations.

Returns Nothing if no sheet exists with that name. In fact any approach that tries to return a worksheet may return Nothing, so you should always check if a valid worksheet was set.

Note
ws and wb are commonly used short names and prefixes for Worksheet and Workbook

Using the Parent Worksheet of a Range

Sometimes, your macro uses multiple range variables located on different worksheets. Both the Parent and the Worksheet Method give access to the Worksheet object.

Previous and Next Worksheet

You can also Set a Worksheet variable to a Previous or Next worksheet, as seen from a specified Worksheet.

Источник

VBA ActiveSheet – Excel Active Sheet Object

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:

50+ Excel Templates

50+ PowerPoint Templates

25+ Word 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
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

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.

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.

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.

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.

Get the Name of the ActiveSheet

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

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.

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.

Count Charts in ActiveSheet

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

Protect in ActiveSheet using VBA

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

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

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.

Источник

VBA Activate Worksheet in Excel

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:

50+ Excel Templates

50+ PowerPoint Templates

25+ Word 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
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

VBA Activate Worksheet method is used to makes the current sheet as active sheet. Here we are the examples using Activate method of worksheet object in VBA. It is very frequently used method while writing VBA macros. We also see the VBA ActiveSheet object with examples.

When we need to use Activate Worksheet method in VBA?

We use Activate worksheet method to activate current sheet as active sheet. When we are working with multiple sheets in a workbook, if we want to move or go to another sheet in the same workbook or another workbook we use activate worksheet method.

VBA Activate Worksheet Method- Syntax

Here is the example syntax to activate Worksheet using VBA. You can use either a Worksheet name or Worksheet number. Always best practice is to use sheet name.

Worksheets(“Your Worksheet Name”).Activate
‘Or
Worksheets(“Worksheet Number”).Activate

Where Activate is the method of Workbook object is used to makes current sheet as active sheet.

VBA Activate Worksheet – with Name: Example 1

Please see the below VBA codes to activate Worksheet. In this example we are activating a Worksheet named “Project1”.

VBA Activate Worksheet Method– with Number: Example 2

Please see the below VBA code or macro procedure to activate Worksheet. In this example we are activating first Worksheet in the active workbook.

VBA ActiveSheet Object

We can refer the currently activated worksheet using Excel VBA ActiveSheet object. ActiveSheet VBA object is very usefull while automating tasks and working on currently active sheet in the active workbook window. If you ignore the ActiveSheet object while refering any other object like range or chart, VBA will treat the ActiveSheet as the current sheet by default. For example: Following are the two macro statements both will refer the active sheet.

both the above statements print some value at Range A1 of Activesheet.

Set ActiveSheet in Excel VBA

It is very convinient refer the Active Sheet in Excel VBA by setting into a Variable. We can assign and set ActiveSheet to an object and refer at any place of the procedure. Here is the syntax to Set ActiveSheet in VBA.

This code will print the some value at Range A1 of Activesheet.

VBA Activate Worksheet Method- Best Approach

Note: Always better to use the Worksheet name, instead of Worksheet number. The best is to assign the Worksheet to an object and then do whatever task you want to do with that particular Worksheet object.

When working with multiple Worksheets, you should refer the Worksheet with exact Worksheet name to correctly update your data into target Worksheet. Create Worksheet object and refer the Worksheet with the object whenever you require.

Let us see another example to understand the accessing the Worksheets using objects. You do not need to activate Worksheet to deal with any Worksheet.

VBA Activate Worksheet Method- Instructions

Please follow the below step by step instructions to execute the above mentioned VBA macros or codes:

  1. Open an Excel Worksheet
  2. Press Alt+F11 :This will Open the VBA Editor. Otherwise, you can open it from the Developer Tab
  3. Insert a Module from Insert Menu
  4. Copy the above code for activating worksheet and Paste in the code window(VBA Editor)
  5. Save the file as macro enabled Worksheet
  6. Press ‘F5’ to run it or Keep Pressing ‘F8’ to debug the code line by line and check how the sheet is activating.
Related Resource

You have seen how to activate worksheets using Excel VBA and referring the AciveSheet. Following are the example macros to Activate Excel Workbook and Range.

Источник

VBA Select Sheet, Activate Sheet, and Get Activesheet

In this Article

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:

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

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

ActiveSheet Name

To get the 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).

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

Select Worksheet by Index Number

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

Select Worksheet With VBA Code Name

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:

More Activate / Select Sheet Examples

Set ActiveSheet to Variable

This will assign the ActiveSheet to a Worksheet Object Variable.

Change ActiveSheet Name

With ActiveSheet

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

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.

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.

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!

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Skip to content

VBA Activate Worksheet in Excel

  • VBA Activate Method Excel Worksheet Object

VBA Activate Worksheet method is used to makes the current sheet as active sheet. Here we are the examples using Activate method of worksheet object in VBA. It is very frequently used method while writing VBA macros. We also see the VBA ActiveSheet object with examples.

VBA Activate Method Excel Worksheet Object

  • Why we need to Activate a Worksheet?
  • VBA Activate Worksheet – Syntax
  • VBA Activate Worksheet Method: Example 1
  • VBA Activate Worksheet Method: Example 2
  • VBA ActiveSheet Object
  • Set ActiveSheet in Excel VBA
  • VBA Activate Worksheet Method- Best Approach
  • VBA Activate Worksheet Method- Instructions

When we need to use Activate Worksheet method in VBA?

We use Activate worksheet method to activate current sheet as active sheet. When we are working with multiple sheets in a workbook, if we want to move or go to another sheet in the same workbook or another workbook we use activate worksheet method.

VBA Activate Worksheet Method- Syntax

Here is the example syntax to activate Worksheet using VBA. You can use either a Worksheet name or Worksheet number. Always best practice is to use sheet name.

Worksheets(“Your Worksheet Name”).Activate
‘Or
Worksheets(“Worksheet Number”).Activate

Where Activate is the method of Workbook object is used to makes current sheet as active sheet.

VBA Activate Worksheet – with Name: Example 1

Please see the below VBA codes to activate Worksheet. In this example we are activating a Worksheet named “Project1”.

Sub Activate_Sheet()
    Worksheets("Project1").Activate
    'Or
    Sheets("Project1").Activate
End Sub

VBA Activate Worksheet Method– with Number: Example 2

Please see the below VBA code or macro procedure to activate Worksheet. In this example we are activating first Worksheet in the active workbook.

Sub Activate_Sheet_BasedOnIndex()
    Worksheets(1).Activate
    'Or
    Sheets(1).Activate
End Sub

VBA ActiveSheet Object

We can refer the currently activated worksheet using Excel VBA ActiveSheet object. ActiveSheet VBA object is very usefull while automating tasks and working on currently active sheet in the active workbook window. If you ignore the ActiveSheet object while refering any other object like range or chart, VBA will treat the ActiveSheet as the current sheet by default. For example: Following are the two macro statements both will refer the active sheet.

ActiveSheet.Range("A1")="Some Value"
Range("A1")="Some Value"

both the above statements print some value at Range A1 of Activesheet.

Set ActiveSheet in Excel VBA

It is very convinient refer the Active Sheet in Excel VBA by setting into a Variable. We can assign and set ActiveSheet to an object and refer at any place of the procedure. Here is the syntax to Set ActiveSheet in VBA.

Sub sbSetAcitveSheetVBA()

Dim ws As Worksheet
Set ws = ActiveSheet

ws.Range("A1") = "Some Value"
End Sub

This code will print the some value at Range A1 of Activesheet.

VBA Activate Worksheet Method- Best Approach

Note: Always better to use the Worksheet name, instead of Worksheet number. The best is to assign the Worksheet to an object and then do whatever task you want to do with that particular Worksheet object.

When working with multiple Worksheets, you should refer the Worksheet with exact Worksheet name to correctly update your data into target Worksheet. Create Worksheet object and refer the Worksheet with the object whenever you require.

Let us see another example to understand the accessing the Worksheets using objects. You do not need to activate Worksheet to deal with any Worksheet.

Sub sb_Activate_Workbook_Object()
'Declare the objects here
    Dim wsMain As Worksheet, ws_A As Worksheet
    
'Set the worksheet to Object
    Set wsMain = ThisWorkbook
    Set ws_A = Worksheets("Test")

'Now deal with your worksheets
    ws_A.Range("A1") = wsMain.Sheet1.Range("A1")

End Sub

VBA Activate Worksheet Method- Instructions

Please follow the below step by step instructions to execute the above mentioned VBA macros or codes:

  1. Open an Excel Worksheet
  2. Press Alt+F11 :This will Open the VBA Editor. Otherwise, you can open it from the Developer Tab
  3. Insert a Module from Insert Menu
  4. Copy the above code for activating worksheet and Paste in the code window(VBA Editor)
  5. Save the file as macro enabled Worksheet
  6. Press ‘F5’ to run it or Keep Pressing ‘F8’ to debug the code line by line and check how the sheet is activating.
Related Resource

You have seen how to activate worksheets using Excel VBA and referring the AciveSheet. Following are the example macros to Activate Excel Workbook and Range.

  • VBA to Activate Range
  • VBA to Activate Workbook
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
      • In this topic:
  • When we need to use Activate Worksheet method in VBA?
  • VBA Activate Worksheet Method- Syntax
  • VBA Activate Worksheet – with Name: Example 1
  • VBA Activate Worksheet Method– with Number: Example 2
  • VBA ActiveSheet Object
  • Set ActiveSheet in Excel VBA
  • VBA Activate Worksheet Method- Best Approach
  • VBA Activate Worksheet Method- Instructions

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:
By PNRaoLast Updated: March 2, 2023

One Comment

  1. jojo
    February 14, 2019 at 7:15 PM — Reply

    Hello, in your last example you declare wsMain as WorkSheet and go on to set it as a Workbook and treat it as a Workbook, it this possible to do?

    Thanks for your very helpful work.

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

Go to Top

Содержание

  • ActiveSheet
  • Выбранные листы против ActiveSheet
  • Выберите рабочий лист
  • Дополнительные примеры активации / выбора листов

В этой статье будет обсуждаться объект ActiveSheet в VBA. Также будет обсуждаться, как активировать, выбирать и переходить к рабочим листам (и многое другое). Прочтите наше полное руководство по рабочим листам VBA для получения дополнительной информации о работе с рабочими листами в VBA.

В VBA ActiveSheet относится к текущему активному рабочему листу. Одновременно может быть активен только один лист.

Активировать рабочий лист (настройка ActiveSheet)

Чтобы установить ActiveSheet, используйте Worksheet.Activate:

1 Рабочие листы («Ввод»). Активировать

Команда «Активировать лист» фактически «перейдет» к листу, изменив видимый лист.

В приведенном выше примере используется имя листа (вкладка). Вместо этого вы можете использовать кодовое имя VBA для рабочего листа:

Имя ActiveSheet

Чтобы получить имя ActiveSheet:

1 msgbox ActiveSheet.name

Выбранные листы против ActiveSheet

В любой момент времени ActiveSheet может быть только один лист. Однако можно выбрать сразу несколько листов.

Когда выбрано несколько листов, активным считается только самый верхний лист (ActiveSheet).

Выберите рабочий лист

Если вы хотите выбрать лист вместо его активации. Вместо этого используйте .Select.

Выбрать лист по имени вкладки

Это выбирает рабочий лист на основе его имени вкладки листа

1 Таблицы («Ввод»). Выбрать

Выбрать лист по порядковому номеру

Это выбирает рабочий лист на основе его положения относительно других вкладок.

1 Рабочие листы (1) .Выбрать

Выберите рабочий лист с кодовым именем VBA

Выбор листов по имени кода может предотвратить ошибки, вызванные изменением имени листа.

Выбрать текущий лист

Чтобы выбрать текущий рабочий лист, используйте объект ActiveSheet:

Дополнительные примеры активации / выбора листов

Установите ActiveSheet на переменную

Это назначит ActiveSheet переменной объекта рабочего листа.

123 Dim ws как рабочий листУстановить ws = ActiveSheet

Изменить имя ActiveSheet

Это изменит имя ActiveSheet.

1 ActiveSheet.Name = «NewName»

С ActiveSheet

Использование оператора With позволяет оптимизировать код при работе с объектами (такими как листы или ActiveSheet).

12345 С ActiveSheet.Name = «StartFresh».Cells.Clear.Range («A1»). Value = .NameКонец с

Обратите внимание, что вам не нужно повторять ActiveSheet перед каждой строкой кода. Это может значительно сэкономить время при работе с длинным списком команд.

Перебирать выбранные листы

Следующий макрос будет проходить по всем выбранным листам, отображая их имена.

12345678 Sub GetSelectedSheetsName ()Dim ws как рабочий листДля каждого ws в ActiveWindow.SelectedSheetsMsgBox ws.NameСледующий wsКонец подписки

Перейти к следующему листу

Этот код перейдет на следующий лист. Если ActiveSheet является последним листом, он перейдет к первому листу в рабочей книге.

12345 Если ActiveSheet.Index = Worksheets.Count, тоРабочие листы (1) .АктивироватьЕщеActiveSheet.Next.ActivateКонец, если

Вы поможете развитию сайта, поделившись страницей с друзьями

I just need to activate a certain worksheet. I have a string variable that keeps the name of the worksheet.

ashleedawg's user avatar

ashleedawg

20k8 gold badges73 silver badges104 bronze badges

asked Oct 25, 2010 at 10:44

Alex's user avatar

1

Would the following Macro help you?

Sub activateSheet(sheetname As String)
'activates sheet of specific name
    Worksheets(sheetname).Activate
End Sub

Basically you want to make use of the .Activate function. Or you can use the .Select function like so:

Sub activateSheet(sheetname As String)
'selects sheet of specific name
    Sheets(sheetname).Select
End Sub

answered Oct 25, 2010 at 11:08

Dennis G's user avatar

Dennis GDennis G

21.3k19 gold badges96 silver badges133 bronze badges

1

I would recommend you to use worksheet’s index instead of using worksheet’s name, in this way you can also loop through sheets «dynamically»

for i=1 to thisworkbook.sheets.count
 sheets(i).activate
'You can add more code 
with activesheet
 'Code...
end with
next i

It will also, improve performance.

answered Jan 6, 2017 at 23:09

Moreno's user avatar

MorenoMoreno

5881 gold badge8 silver badges22 bronze badges

1

An alternative way to (not dynamically) link a text to activate a worksheet without macros is to make the selected string an actual link.
You can do this by selecting the cell that contains the text and press CTRL+K then select the option/tab ‘Place in this document’ and select the tab you want to activate.
If you would click the text (that is now a link) the configured sheet will become active/selected.

answered Nov 30, 2015 at 15:36

Daan's user avatar

DaanDaan

493 bronze badges

Понравилась статья? Поделить с друзьями:
  • Set excel getobject excel application
  • Serial numbering in excel
  • Set excel from a cells value
  • Serial date to date excel
  • Set excel createobject excel application