Узнать имя активного листа |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
Содержание
- 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Конец, если |
Вы поможете развитию сайта, поделившись страницей с друзьями
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.
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
VBA ActiveSheet – Excel Active Sheet Object
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"
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
Related Posts
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
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.
Page load link
Go to Top
title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Application.ActiveSheet property (Excel) |
vbaxl10.chm132078 |
vbaxl10.chm132078 |
excel |
Excel.Application.ActiveSheet |
6ed42d87-2ad5-eecc-ad5b-4c92617a04bc |
04/04/2019 |
high |
Application.ActiveSheet property (Excel)
Returns an object that represents the active sheet (the sheet on top) in the active workbook or in the specified window or workbook. Returns Nothing if no sheet is active.
Syntax
expression.ActiveSheet
expression A variable that represents an Application object.
Remarks
If you don’t specify an object qualifier, this property returns the active sheet in the active workbook.
If a workbook appears in more than one window, the ActiveSheet property may be different in different windows.
Example
This example displays the name of the active sheet.
MsgBox "The name of the active sheet is " & ActiveSheet.Name
This example creates a print preview of the active sheet that has the page number at the top of column B on each page.
Sub PrintSheets() 'Set up your variables. Dim iRow As Integer, iRowL As Integer, iPage As Integer 'Find the last row that contains data. iRowL = Cells(Rows.Count, 1).End(xlUp).Row 'Define the print area as the range containing all the data in the first two columns of the current worksheet. ActiveSheet.PageSetup.PrintArea = Range("A1:B" & iRowL).Address 'Select all the rows containing data. Rows(iRowL).Select 'display the automatic page breaks ActiveSheet.DisplayAutomaticPageBreaks = True Range("B1").Value = "Page 1" 'After each page break, go to the next cell in column B and write out the page number. For iPage = 1 To ActiveSheet.HPageBreaks.Count ActiveSheet.HPageBreaks(iPage) _ .Location.Offset(0, 1).Value = "Page " & iPage + 1 Next iPage 'Show the print preview, and afterwards remove the page numbers from column B. ActiveSheet.PrintPreview Columns("B").ClearContents Range("A1").Select End Sub
[!includeSupport and feedback]