title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Sheets.Item property (Excel) |
vbaxl10.chm152078 |
vbaxl10.chm152078 |
excel |
Excel.Sheets.Item |
c0409baa-67df-745a-513b-8a162f051ce4 |
05/15/2019 |
medium |
Sheets.Item property (Excel)
Returns a single object from a collection.
Syntax
expression.Item (Index)
expression A variable that represents a Sheets object.
Parameters
Name | Required/Optional | Data type | Description |
---|---|---|---|
Index | Required | Variant | The name or index number of the object. |
Example
This example activates Sheet1.
Sheets.Item("sheet1").Activate
[!includeSupport and feedback]
попробую…
у листа рабочей книги (объекты worksheet, chart) есть свойства index, name, codename
index — текущий номер листа по порядку (включая скрытые), может меняться пользователем при изменении порядка и количества листов;
name — то, что отбражается на ярлычке, может меняться пользователем (конечно. если книга не защищена);
codename — «внутреннее» имя листа, «обычному» пользователю невидимое и недоступное, поэтому не может меняться пользователем.
кроме того, codename является свойством read-only и через VBA также не может быть изменено.
*)
в VBE в окне проекта в списке объектов сначала указаны кодовые имена листов, а затем, в скобках, «обычные» имена.
«обычные» и «необычные» («кодовые») имена могут совпадать, могут — нет.
но в пределах каждого из множеств имён имя должно быть уникальным (без учета регистра символов)
изменить codename можно через интерфейс VBE — ЛКМ по имени листа в списке объектов — F4 — свойство (Name) — именно которое со скобками.
доступ к отдельному листу возможен:
— по индексу
— по «обычному» имени
и для того, и для другого, используется свойство item коллекций sheets, worksheets, charts объекта workbook:
sheets.item(2)
charts.item(«диаграмма 5»)
и т.п.
т.к. свойство item является «умолчальным», то допустимы и конструкции
sheets(2)
charts(«диаграмма 5»)
прямого доступа по «кодовому» имени листа через коллекцию — нет.
но, зная codename листа на этапе разработки проекта (макроса). можно прямо это имя написать в качестве идентификатора листа:
лист1.[a1] — обращение к ячейке A1 листа с
кодовым именем
«лист1» («Лист1» и т.п.)
если же нужно получить лист по кодовому имени, но на этапе разработки оно было неизвестно, то примерно так:
Visual Basic | ||
|
зачем оно всё надо — надеюсь, понятно?
_________________________
*) однако, может: Как узнать Item листа в книге Excel
Данная коллекция представляет собой коллекцию листов (Sheets) в книге (WorkBook). Первое, что мы с Вами сделаем это получим количество листов в книге.
Sub Test() MsgBox (Str(Application.Workbooks.Item("Test.xls").Sheets.Count)) End Sub
Но под листом понимается не только клетки, но и диаграмма. Так же как и лист для расчетов диаграмма будет включена в подсчет листов. Как посмотреть имена листов. Просто. Есть свойтсво Name:
Sub Test() With Application.Workbooks.Item("Test.xls") For x = 1 To .Sheets.Count MsgBox (Sheets.Item(x).Name) Next x End With End Sub
А как же лист с формулами отличить от диаграммы ? Попробуйте так. Type вернет Вам тип. Только не знаю документированный способ это или нет.
Sub Test() With Application.Workbooks.Item("Test.xls") For x = 1 To .Sheets.Count MsgBox (Sheets.Item(x).Type) If Sheets.Item(x).Type = 3 Then MsgBox Sheets.Item(x).Name Next x End With End Sub
К коллекции листов есть возможность добавлять свои листы, для этого существует метод Add. Этот метод требует 4 параметра Add(Before, After, Count, Type). Все эти параметры необязательные. Первые два отвечают за место вставки листа. Дальше количество вставляемых листов Count и тип листа. Типы могут быть, например, такие. xlWorkSheet для расчетного листа, xlChart для диаграммы. Если местоположение не указывать, то лист будет вставляться относительно текущего листа.
Sub Test() With Application.Workbooks.Item("Test.xls") Sheets.Add End With End Sub
Метод Parent позволяет узнать какой книге принадлежит текущий лист.
Sub Test() With Application.Workbooks.Item("Test.xls") MsgBox (Sheets.Parent.Name) End With End Sub
Если у Вас есть желание, то некоторые листы можно убрать из обзора. Это бывает полезно, если у Вас есть константы или расчеты, которые Вы не хотите чтобы видели на экране в виде листов. Для этого можно использовать метод Visible. Устанавливая это свойство в TRUE или FALSE вы сможете убирать и показывать лист.
Sub Test() With Application.Workbooks.Item("Test.xls") .Sheets.Item("Лист5").Visible = False End With End Sub
In this article I will explain how to work with the worksheet object. One the most important thing to know when working with worksheets is understanding the difference between the items below:
- Sheet Object’s Variable Name
- Sheet Name
- Sheet Index
I will also explain how to copy and create new worksheets programmatically.
Jump to:
- Referencing Sheets by Using the Sheet Object Directly
- Sheet Name
- Referencing Sheets Using Their Name
- Sheet Index
- Referencing Sheets Using Their Index
- Creating New Worksheets
- Creating and Inserting Sheets After a Specific Sheet (:=After)
- Creating and Inserting Sheets Before a Specific Sheet (:=Before)
- Inserting Multiple Sheets (:=Count)
- Inserting different types of sheets (:=Type)
- Copying Sheets
Referencing Sheets by Using the Sheet Object Directly:
From an object oriented programming perspective, each sheet is an object. The address of each object is stored in a variable. To figure out what variable references each sheet you could use the project explorer in the VBA editor. The highlighted part in the figure below shows the name of the sheet objects variables:
The table below shows the variable associated with each sheet:
To reference cells and ranges using the sheet object directly you could follow the sample codes below:
Sub Example1()
Sheet1.Cells(1, 1) = "Some Data"
Sheet2.Range("A1") = "some Data"
Sheet3.Range("A1:A1") = Sheet2.Range("A1")
End Sub
Note the only way to modify the name of the sheet objects variable is through the property window in the VBA editor:
As you can see in the table below Sheet2‘s object’s name has been change to Object_Sheet2:
By changing the name of sheet2‘s object to Object_Sheet2 the same line of code above will become:
Sub Example2()
Sheet1.Cells(1, 1) = "Some Data"
'note the change in this line
Object_Sheet2.Range("A1") = "some Data"
Sheet3.Range("A1:A1") = Sheet2.Range("A1")
End Sub
Sheet Name:
The sheet names are the values shown in the bottom panel of the excel workbook:
As you can see this workbook has three sheets with the names “Sheet1”, “New Name for Sheet3” and “Sheet2”. You could also see the sheet names using the project window. The values in the parenthesis:
Below you can see the sheet object’s names and the sheet names:
In order to change the sheet name there are 3 methods:
Method 1: Using the property window:
Method 2: Renaming the sheet using the panel at the bottom of the workbook:
Method 3: Unlike the sheet object variables name which could only be changed using the property window, you can change the sheets name programmatically:
Sub Example3()
Sheet1.Name = "Changing Sheet1's Name"
End Sub
After making the change to sheet1’s name, we will have:
Referencing Sheets Using Their Name:
You could also reference a sheet using the sheet name and the WorkSheets collection. In the example below there are 3 sheets with the names “MySheet1”, “MySheet2” and “MySheet3”. They are referenced using the sheet names through the WorkSheets collection.
Sub Example4()
Sheets("MySheet1").Cells(1, 1) = "some Data"
'sheets and worksheets are the same
Worksheets("MySheet2").Range("A1") = "some data"
Sheets("MySheet3").Range("A1:A1") = Worksheets("MySheet2").Range("A1")
End Sub
The syntax for referencing sheets using their name is Sheets(“Sheet Name”) and Worksheets(“Sheet Name”). Both return the same results.
Note: Keep in mind that the sheet name could be modified by the user. This may cause errors in your code if your program references sheets using their name. You might need to consider locking to workbook from such changes.
Sheet Index:
Each sheet is associated an index value, starting from the value “1”. The index value depends on the order of the sheets. See the example below:
In the picture above the indexes and sheet names are as follows:
By moving the sheets around the indexes will also change. See the example below:
Referencing Sheets Using Their Index:
You could also reference a sheet using the sheet index and the WorkSheets collection. In the example below there are 3 sheets:
They are referenced using the sheet index through the WorkSheets collection:
Sub Example5()
Sheets(1).Cells(1, 1) = "some Data"
'sheets and worksheets are the same
Worksheets(2).Range("A1") = "some data"
Sheets.Item(3).Range("A1:A1") = Worksheets.Item(2).Range("A1")
End Sub
Note: Keep in mind that the user can change the order of the sheets. This may cause error in your code if you are referencing sheets using their index. You might need to consider locking the workbook from such changes.
Creating New Worksheets:
In the following examples I will assume I have 3 sheets, with the attributes below:
Creating and Inserting Sheets After a Specific Sheet (:=After):
The code below add a sheet after sheet3. Note all the samples yield the same result:
'using sheet object
Call Worksheets.Add(after:=Sheet3)
'using sheet name
Call Worksheets.Add(after:=Worksheets("MySheet3"))
'using sheet name
Call Worksheets.Add(after:=Sheets("MySheet3"))
'using sheet index
Call Worksheets.Add(after:=Worksheets.Item(3))
'using sheet index
Call Worksheets.Add(after:=Sheets.Item(3))
Creating and Inserting Sheets Before a Specific Sheet (:=Before):
The code below add a sheet before sheet2 and names it “MySheet4”. Note all the samples yield the same result:
Dim wrkSheet_Temp As Worksheet
'using sheet object
Set wrkSheet_Temp = Worksheets.Add(before:=Sheet2)
wrkSheet_Temp.Name = "MySheet4"
'using sheet name
Set wrkSheet_Temp = Worksheets.Add(before:=Worksheets("MySheet2"))
wrkSheet_Temp.Name = "MySheet4"
'using sheet name
Set wrkSheet_Temp = Worksheets.Add(before:=Sheets("MySheet2"))
wrkSheet_Temp.Name = "MySheet4"
'using sheet index
Set wrkSheet_Temp = Worksheets.Add(before:=Worksheets.Item(2))
wrkSheet_Temp.Name = "MySheet4"
'using sheet index
Set wrkSheet_Temp = Worksheets.Add(before:=Sheets.Item(2))
wrkSheet_Temp.Name = "MySheet4"
Inserting Multiple Sheets (:=Count):
The codes below insert 5 new sheets after the last sheet:
Dim i As Integer
'using the count:= property
Call Worksheets.Add(after:=Worksheets.Item(Worksheets.Count), Count:=5)
'using Iteration
For i = 1 To 5
Call Worksheets.Add(after:=Worksheets.Item(Worksheets.Count))
Next i
Inserting different types of sheets (:=Type):
There are 4 types of sheets you can add, xlWorksheet, xlChart, XlExcel4MacroSheet and xlExcel4IntlMacroSheet:
Sub example6()
'adds a sheet of type worksheet
Call Worksheets.Add(Type:=xlWorksheet)
'adds a sheet of type chart
Call Worksheets.Add(Type:=xlChart)
'adds a sheet of type macro
Call Worksheets.Add(Type:=xlExcel4MacroSheet)
'adds a sheet of type macro
Call Worksheets.Add(Type:=xlExcel4IntlMacroSheet)
End Sub
Copying Sheets:
Copying sheets is similar to creating sheets. I will assume I have the same set of sheets as the example I’ve used in Creating New Worksheet:
Similar to creating new sheets you could choose to copy after or before a certain sheet using the :=after and :=before attributes. For more information regarding the :=after and :=before attributes please see Creating New Worksheet. The code below copies sheet1 after sheet3 using the sheet name:
'Using the sheet name
Call Worksheets("MySheet1").Copy(after:=Sheet3)
The code below copies sheet1 before sheet2 using the sheet index:
'using the sheet index
Call Worksheets(1).Copy(before:=Worksheets("MySheet3"))
The code below copies sheet1 after sheet2 using the sheet object:
'using the sheet object
Call Sheet1.Copy(after:=Sheets("MySheet2"))
If you need assistance with your code, or you are looking to hire a VBA programmer feel free to contact me. Also please visit my website www.software-solutions-online.com
In this Article
- Sheets Vs. Worksheets
- Referencing Sheets
- ActiveSheet
- Sheet Name
- Sheet Index Number
- Sheet “Code Name”
- Referencing Sheets in Other Workbooks
- Activate vs. Select Sheet
- Activate a Sheet
- Select a Sheet
- Select Multiple Sheets
- Worksheet Variable
- Loop Through All Sheets in Workbook
- Worksheet Protection
- Workbook Protection
- Worksheet Protection
- Protect Worksheet
- Unprotect Worksheet
- Worksheet Visible Property
- Unhide Worksheet
- Hide Worksheet
- Very Hide Worksheet
- Worksheet-Level Events
- Worksheet Activate Event
- Worksheet Change Event
- Worksheet Cheat Sheet
- VBA Worksheets Cheatsheet
This is the ultimate guide to working with Excel Sheets / Worksheets in VBA.
At the bottom of this guide, we’ve created a cheat sheet of common commands for working with sheets.
Sheets Vs. Worksheets
There are two ways to reference Sheets using VBA. The first is with the Sheets object:
Sheets("Sheet1").Activate
The other is with the Worksheets object:
Worksheets("Sheet1").Activate
99% of the time, these two objects are identical. In fact, if you’ve searched online for VBA code examples, you’ve probably seen both objects used. Here is the difference:
The Sheets Collection contains Worksheets AND Chart Sheets.
So use Sheets if you want to include regular Worksheets AND Chart Sheets. Use Worksheets if you want to exclude Chart Sheets. For the rest of this guide we will use Sheets and Worksheets interchangeably.
Referencing Sheets
There are several different ways to reference Sheets:
- ActiveSheet
- Sheet Tab Name
- Sheet Index Number
- Sheet Code Name
ActiveSheet
The ActiveSheet is the Sheet that’s currently active. In other words, if you paused your code and looked at Excel, it’s the sheet that is visible. The below code example will display a MessageBox with the ActiveSheet name.
MsgBox ActiveSheet.Name
Sheet Name
You are probably most familiar with referencing Sheets by their Tab Name:
Sheets("TabName").Activate
This is the sheet name that’s visible to Excel users. Enter it into the sheets object, as a string of text, surrounded by quotations.
Sheet Index Number
The Sheet Index number is the sheet position in the workbook. 1 is the first sheet. 2 is the second sheet etc.:
Sheets(1).Activate
Sheet Index Number – Last Sheet in Workbook
To reference the last Sheet in the workbook, use Sheets.Count to get the last Index Number and activate that sheet:
Sheets(Sheets.Count).Activate
Sheet “Code Name”
The Sheet Code Name is it’s Object name in VBA:
CodeName.Activate
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!
Learn More
Referencing Sheets in Other Workbooks
It’s also easy to reference Sheets in other Workbooks. To do so, you need to use the Workbooks Object:
Workbooks("VBA_Examples.xlsm").Worksheets("Sheet1").Activate
Important: The Workbook must be open before you can reference its Sheets.
Activate vs. Select Sheet
In another article we discuss everything about activating and selecting sheets. The short version is this:
When you Activate a Sheet it becomes the ActiveSheet. This is the sheet you would see if you looked at your Excel program. Only one sheet may be activate at a time.
Activate a Sheet
Sheets("Sheet1").Activate
When you select a Sheet, it also becomes the ActiveSheet. However, you can select multiple sheets at once. When multiple sheets are selected at once, the “top” sheet is the ActiveSheet. However, you can toggle the ActiveSheet within selected sheets.
VBA Programming | Code Generator does work for you!
Select a Sheet
Sheets("Sheet1").Select
Select Multiple Sheets
Use an array to select multiple sheets at once:
Worksheets(Array("Sheet2", "Sheet3")).Select
Worksheet Variable
Assigning a worksheet to an object variable allows you to reference the worksheet by it’s variable name. This can save a lot of typing and make your code easier to read. There are also many other reasons you might want to use variables.
To declare a worksheet variable:
Dim ws as worksheet
Assign a worksheet to a variable:
Set ws = Sheets("Sheet1")
Now you can reference the worksheet variable in your code:
ws.Activate
Loop Through All Sheets in Workbook
Worksheet variables are useful when you want to loop through all the worksheets in a workbook. The easiest way to do this is:
Dim ws as Worksheet
For Each ws in Worksheets
MsgBox ws.name
Next ws
This code will loop through all worksheets in the workbook, displaying each worksheet name in a message box. Looping through all the sheets in a workbook is very useful when locking / unlocking or hiding / unhiding multiple worksheets at once.
Worksheet Protection
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Workbook Protection
Workbook protection locks the workbook from structural changes like adding, deleting, moving, or hiding worksheets.
You can turn on workbook protection using VBA:
ActiveWorkbook.Protect Password:="Password"
or disable workbook protection:
ActiveWorkbook.UnProtect Password:="Password"
Note: You can also protect / unprotect without a password by omitting the Password argument:
ActiveWorkbook.Protect
Worksheet Protection
Worksheet-level protection prevents changes to individual worksheets.
Protect Worksheet
Worksheets("Sheet1").Protect "Password"
Unprotect Worksheet
Worksheets("Sheet1").Unprotect "Password"
There are a variety of options when protecting worksheets (allow formatting changes, allow user to insert rows, etc.) We recommend using the Macro Recorder to record your desired settings.
We discuss worksheet protection in more detail here.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Worksheet Visible Property
You might already know that worksheets can be hidden:
There are actually three worksheet visibility settings: Visible, Hidden, and VeryHidden. Hidden sheets can be unhidden by any regular Excel user – by right-clicking in the worksheet tab area (shown above). VeryHidden sheets can only be unhidden with VBA code or from within the VBA Editor. Use the following code examples to hide / unhide worksheets:
Unhide Worksheet
Worksheets("Sheet1").Visible = xlSheetVisible
Hide Worksheet
Worksheets("Sheet1").visible = xlSheetHidden
Very Hide Worksheet
Worksheets("Sheet1").Visible = xlSheetVeryHidden
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Worksheet-Level Events
Events are triggers that can cause “Event Procedures” to run. For example, you can cause code to run every time any cell on a worksheet is changed or when a worksheet is activated.
Worksheet event procedures must be placed in a worksheet module:
There are numerous worksheet events. To see a complete list, go to a worksheet module, select “Worksheet” from the first drop-down. Then selecting an event procedure from the second drop-down to insert it into the module.
Worksheet Activate Event
Worksheet activate events run each time the worksheet is opened.
Private Sub Worksheet_Activate()
Range("A1").Select
End Sub
This code will select cell A1 (resetting the view area to the top-left of the worksheet) each time the worksheet is opened.
Worksheet Change Event
Worksheet change events run whenever a cell value is changed on the worksheet. Read our tutorial about Worksheet Change Events for more information.
Worksheet Cheat Sheet
Below you will find a cheat sheet containing common code examples for working with sheets in VBA
VBA Worksheets Cheatsheet
VBA worksheets Cheatsheet
Description | Code Example |
---|---|
Referencing and Activating Sheets | |
Tab Name | Sheets(«Input»).Activate |
VBA Code Name | Sheet1.Activate |
Index Position | Sheets(1).Activate |
Select Sheet | |
Select Sheet | Sheets(«Input»).Select |
Set to Variable | Dim ws as Worksheet Set ws = ActiveSheet |
Name / Rename | ActiveSheet.Name = «NewName» |
Next Sheet | ActiveSheet.Next.Activate |
Loop Through all Sheets | Dim ws as Worksheet
For each ws in Worksheets |
Loop Through Selected Sheets | Dim ws As Worksheet
For Each ws In ActiveWindow.SelectedSheets |
Get ActiveSheet | MsgBox ActiveSheet.Name |
Add Sheet | Sheets.Add |
Add Sheet and Name | Sheets.Add.Name = «NewSheet» |
Add Sheet With Name From Cell | Sheets.Add.Name = range(«a3»).value |
Add Sheet After Another | Sheets.Add After:=Sheets(«Input») |
Add Sheet After and Name | Sheets.Add(After:=Sheets(«Input»)).Name = «NewSheet» |
Add Sheet Before and Name | Sheets.Add(Before:=Sheets(«Input»)).Name = «NewSheet» |
Add Sheet to End of Workbook | Sheets.Add After:=Sheets(Sheets.Count) |
Add Sheet to Beginning of Workbook | Sheets.Add(Before:=Sheets(1)).Name = «FirstSheet» |
Add Sheet to Variable | Dim ws As Worksheet Set ws = Sheets.Add |
Copy Worksheets | |
Move Sheet to End of Workbook | Sheets(«Sheet1»).Move After:=Sheets(Sheets.Count) |
To New Workbook | Sheets(«Sheet1»).Copy |
Selected Sheets To New Workbook | ActiveWindow.SelectedSheets.Copy |
Before Another Sheet | Sheets(«Sheet1»).Copy Before:=Sheets(«Sheet2») |
Before First Sheet | Sheets(«Sheet1»).Copy Before:=Sheets(1) |
After Last Sheet | Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count) |
Copy and Name | Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count) ActiveSheet.Name = «LastSheet» |
Copy and Name From Cell Value | Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count) ActiveSheet.Name = Range(«A1»).Value |
To Another Workbook | Sheets(«Sheet1»).Copy Before:=Workbooks(«Example.xlsm»).Sheets(1) |
Hide / Unhide Sheets | |
Hide Sheet | Sheets(«Sheet1»).visible = False or Sheets(«Sheet1»).visible = xlSheetHidden |
Unhide Sheet | Sheets(«Sheet1»).Visible = True or Sheets(«Sheet1»).Visible = xlSheetVisible |
Very Hide Sheet | Sheets(Sheet1).Visible = xlSheetVeryHidden |
Delete or Clear Sheets | |
Delete Sheet | Sheets(«Sheet1»).Delete |
Delete Sheet (Error Handling) | On Error Resume Next Sheets(«Sheet1»).Delete On Error GoTo 0 |
Delete Sheet (No Prompt) | Application.DisplayAlerts = False Sheets(«Sheet1»).Delete Application.DisplayAlerts = True |
Clear Sheet | Sheets(«Sheet1»).Cells.Clear |
Clear Sheet Contents Only | Sheets(«Sheet1»).Cells.ClearContents |
Clear Sheet UsedRange | Sheets(«Sheet1»).UsedRange.Clear |
Protect or Unprotect Sheets | |
Unprotect (No Password) | Sheets(«Sheet1»).Unprotect |
Unprotect (Password) | Sheets(«Sheet1»).Unprotect «Password» |
Protect (No Password) | Sheets(«Sheet1»).Protect |
Protect (Password) | Sheets(«Sheet1»).Protect «Password» |
Protect but Allow VBA Access | Sheets(«Sheet1»).Protect UserInterfaceOnly:=True |
Unprotect All Sheets | Dim ws As Worksheet
For Each ws In Worksheets |