Vba excel sheets names

Return to VBA Code Examples

In this Article

  • Get Sheet Name
    • Get ActiveSheet Name
    • Get Sheet Name by index Number
    • Get Sheet Name by Code Name
  • Rename Sheet
    • Rename ActiveSheet
    • Rename Sheet by Name
    • Rename Sheet by Sheet Index Number
    • Rename Sheet by Code Name
  • Check if Sheet Name Exists
  • Copy Sheet and Rename

This tutorial will cover interacting with Sheet names in VBA.

Get Sheet Name

Sheet names are stored in the Name property of the Sheets or Worksheets object.  The Sheet Name is the “tab” name that’s visible at the bottom of Excel:

vba sheet tab name

Get ActiveSheet Name

This will display the ActiveSheet name in a message box:

MsgBox ActiveSheet.Name

Get Sheet Name by index Number

This will display the first worksheet name in a message box:

MsgBox Sheets(1).Name

This will display the name of the last worksheet in the workbook:

MsgBox Sheets(Sheets.Count).Name

Get Sheet Name by Code Name

In the VBA Editor, there is an option to change the “code name” of a Sheet. The code name is not visible to the Excel user and can only be seen in the VBA Editor:

vba sheet code name

In VBA, when working with Sheets, you can reference the usual Tab name:

Sheets("TabName").Activate

or the VBA code name:

CodeName.Activate

Referencing the code name is desirable in case the Sheet tab name ever changes. If you allow you Excel user access to changing sheet names you should reference the code name in your VBA code so that a Sheet tab name mismatch doesn’t cause an error. Sheet code names are discussed in more detail here.

To get the Sheet name using the VBA Code name, do the following:

MsgBox CodeName.Name

Rename Sheet

You can rename Sheets by adjusting the name property of the Sheets or Worksheets object.

Rename ActiveSheet

ActiveSheet.Name = "NewName"

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!

automacro

Learn More

Rename Sheet by Name

Sheets("OldSheet").Name = "NewName"

Rename Sheet by Sheet Index Number

Here we use 1 to rename the first Sheet in the Workbook.

Sheets(1).Name = "NewName"

Rename Sheet by Code Name

This code will rename a sheet using it’s VBA code name (discussed above):

Component.Name = "NewName"

VBA Programming | Code Generator does work for you!

Check if Sheet Name Exists

We created a function to test if a Sheet with a particular name already exists.

'Test if a Range Exists on a Sheet.
'Leave range blank to test if sheet exists
'Inputs:
' WhatSheet - String Name of Sheet (ex "Sheet1")
' WhatRange (Optional, Default = "A1") - String Name of Range (ex "A1")
Function RangeExists(WhatSheet As String, Optional ByVal WhatRange As String = "A1") As Boolean
    Dim test As Range
    On Error Resume Next
    Set test = ActiveWorkbook.Sheets(WhatSheet).Range(WhatRange)
    RangeExists = Err.Number = 0
    On Error GoTo 0
End Function

The function will return TRUE if the Sheet exists, or FALSE if it does not.

Use the function like so:

Sub Test_SheetExists()
    MsgBox RangeExists("setup")
End Sub

Copy Sheet and Rename

This example is from our article on Copying Sheets.

After copying and pasting a Sheet, the newly created sheet becomes the ActiveSheet. So to rename a copied Sheet, simply use ActiveSheet.Name:

Sub CopySheetRename2()

    Sheets("Sheet1").Copy After:=Sheets(Sheets.Count)
    On Error Resume Next
    ActiveSheet.Name = "LastSheet"
    On Error GoTo 0

End Sub

Note: We added error handling to avoid errors if the Sheet name already exists.

In this post, you’ll learn about with a detailed explanation of how to get sheet name in Microsoft Excel using VBA.

Table of Contents

  • How to Get Sheet Name in Excel VBA?
    • Get ActiveSheet Name
    • Get Sheet Name by index Number
    • Get Sheet Name by Code Name
    • Check if Sheet Name Exists

Sheet names are stored in the Name property of the Sheets or Worksheets object.  The Sheet Name is the “tab” name that’s visible at the bottom of Excel.

Get ActiveSheet Name

To display the ActiveSheet name in a message box, use the below code snippet

How to Get Sheet Name in Excel VBA?

Get Sheet Name by index Number

To display the worksheet name in a message box by its index number:

To display the name of the last worksheet in the workbook:

MsgBox Sheets(Sheets.Count).Name

Get Sheet Name by Code Name

In the VBA Editor, there is an option to change the “code name” of a Sheet. The code name is not visible to the Excel user and can only be seen in the VBA Editor:

The VBA code name:

To get the Sheet name in a MsgBox using the VBA Code name:

Check if Sheet Name Exists

This is used to check whether the sheet name exists already.

Enter the following code in the module and click run

Code:

Function WorksheetExists2(WorksheetName As String, Optional wb As Workbook) As Boolean

    If wb Is Nothing Then Set wb = ThisWorkbook

    With wb

        On Error Resume Next

        WorksheetExists2 = (.Sheets(WorksheetName).Name = WorksheetName)

        On Error GoTo 0

    End With

End Function

Sub FindSheet()

If WorksheetExists2("Sheet1") Then

    MsgBox "Sheet1 is in this workbook"

Else

    MsgBox "Oops: Sheet does not exist"

End If

End Sub
How to Get Sheet Name in Excel VBA?

In VBA, to name a worksheet does not need any special skills. However, we need to reference which sheet name we are changing by entering the current sheet name. For example, if we want to change the “Sales” sheet, we need to call the sheet by its name using the Worksheet object.

Table of contents
  • Excel VBA Name WorkSheet
    • Examples to Name Worksheet using VBA
      • Example #1
      • Example #2
    • Things to Remember
    • Recommended Articles
Worksheets(“Sales”)

After mentioning the sheet name, we need to select the “Name” property to change the worksheet name.

Worksheets(“Sales”).Name

Now, we need to set the name property to the name as per our wish. For example, assume you want to change the “Sales” to “Sales Sheet,” then put an equal sign after the “NAME” property and enter the new name in double quotes.

Worksheets(“Sales”).Name = “Sales Sheet”

Like this, we can change the worksheet name using the Name property.

Examples to Name Worksheet using VBA

You can download this VBA Name Worksheet Excel Template here – VBA Name Worksheet Excel Template

Example #1

Change or Rename Sheet using Variables.

Look at the below sample code.

Code:

Sub Name_Example1()

 Dim Ws As Worksheet

 Set Ws = Worksheets("Sales")

 Ws.Name = "Sales Sheet"

End Sub

VBA Name Worksheet Example 1

First, we have declared the variable as “Worksheet.”

Dim Ws As Worksheet

Next, we have set the reference to the variable as “Sales” using the worksheet object.

Set Ws = Worksheets("Sales")

Now, the variable “Ws” holds the reference of the worksheet “Sales.”

Now, using the “Ws” variable, we have renamed the worksheet “Sales Sheet.”

This code will change the “Sales” name to “Sales Sheet.”

VBA Name Worksheet Example 1-1

Important Note to Remember

We just have seen how to change the name of the Excel worksheet from one name to another. However, if we run the code again, we will get a Subscript Out of Range errorSubscript out of range is an error in VBA that occurs when we attempt to reference something or a variable that does not exist in the code. For example, if we do not have a variable named x but use the msgbox function on x, we will receive a subscript out of range error.read more.

error 9 Example 1-2

One of the keys to getting an expert in VBA MacrosVBA Macros are the lines of code that instruct the excel to do specific tasks, i.e., once the code is written in Visual Basic Editor (VBE), the user can quickly execute the same task at any time in the workbook. It thus eliminates the repetitive, monotonous tasks and automates the process.read more is to handle errors. However, before handling errors, we need to know why we are getting this error.

We get this error because, in the previous step itself, we have already changed the worksheet named “Sales” to “Sales Sheet.”

We do not have any ” Sales ” sheet; we will get this subscript out of range error.

Example #2

Get all the worksheet names in a single sheet.

Assume you have plenty of worksheets in your workbook. You want to get the name of all these worksheets in any single worksheet. We can do this by using VBA codingVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

For example, look at the below image.

Sheets Example 1-3

We have so many sheets here.

Of all these sheets, we need the name of each sheet in the sheet called “Index Sheet.” Therefore, we have written the below code for you.

Code:

Sub All_Sheet_Names()

Dim Ws As Worksheet
Dim LR As Long

For Each Ws In ActiveWorkbook.Worksheets
LR = Worksheets("Index Sheet").Cells(Rows.Count, 1).End(xlUp).Row + 1
'This LR varaible to find the last used row
Cells(LR, 1).Select
ActiveCell.Value = Ws.Name
Next Ws

End Sub

Now, copy this code to your module.

All sheet Example 1-4

Now, run the code by naming any worksheets “Index Sheet.” This code will give all the worksheet names in the “Index Sheet.”

VBA Name Worksheet Example 1-5

Like this, using the “NAME” property of the worksheet in VBAExcel is a workbook, and worksheets or sheets are included within that workbook. Sheets are what we call them in a regular Excel file, but they’re called «Worksheets» in VBA. The term «Worksheets» refers to all of a worksheet’s collections.read more, we can play around with the name of the worksheets. For example, we can rename, extract, and choose the specific worksheet and do many other things that we can do by using the “Name” property.

Things to Remember

  • The NAME in VBA is property.
  • Using this name, we can rename the worksheet, and also we can extract sheet names.
  • We can change any worksheet name in the specified workbook if you refer to other workbooks than the code-written workbook.
  • If the worksheet name does not match, we will get “Subscript out of range.”

Recommended Articles

This article is a guide to the VBA Name Worksheet. Here, we discuss naming worksheets using VBA coding, practical examples, and a downloadable Excel template. Below you can find some useful Excel VBA articles: –

  • Create a Reference Object using CreateObject
  • Activate Sheet in VBA
  • Rename Sheet in VBA
  • Editor in VBA

Содержание

  1. VBA Sheets – The Ultimate Guide
  2. Sheets Vs. Worksheets
  3. Referencing Sheets
  4. ActiveSheet
  5. Sheet Name
  6. Sheet Index Number
  7. Sheet Index Number – Last Sheet in Workbook
  8. Sheet “Code Name”
  9. VBA Coding Made Easy
  10. Referencing Sheets in Other Workbooks
  11. Activate vs. Select Sheet
  12. Activate a Sheet
  13. Select a Sheet
  14. Select Multiple Sheets
  15. Worksheet Variable
  16. Loop Through All Sheets in Workbook
  17. Worksheet Protection
  18. Workbook Protection
  19. Worksheet Protection
  20. Protect Worksheet
  21. Unprotect Worksheet
  22. Worksheet Visible Property
  23. Unhide Worksheet
  24. Hide Worksheet
  25. Very Hide Worksheet
  26. Worksheet-Level Events
  27. Worksheet Activate Event
  28. Worksheet Change Event
  29. Worksheet Cheat Sheet
  30. VBA Worksheets Cheatsheet
  31. VBA Code Examples Add-in
  32. VBA Get Sheet Name / Rename Sheet
  33. Get Sheet Name
  34. Get ActiveSheet Name
  35. Get Sheet Name by index Number
  36. Get Sheet Name by Code Name
  37. Rename Sheet
  38. Rename ActiveSheet
  39. VBA Coding Made Easy
  40. Rename Sheet by Name
  41. Rename Sheet by Sheet Index Number
  42. Rename Sheet by Code Name
  43. Check if Sheet Name Exists
  44. Copy Sheet and Rename
  45. VBA Code Examples Add-in

VBA Sheets – The Ultimate Guide

In this Article

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:

The other is with the Worksheets object:

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.

Sheet Name

You are probably most familiar with referencing Sheets by their Tab Name:

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.:

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:

Sheet “Code Name”

The Sheet Code Name is it’s Object name in VBA:

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!

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:

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

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.

Select a Sheet

Select Multiple Sheets

Use an array to select multiple sheets at once:

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:

Assign a worksheet to a variable:

Now you can reference the worksheet variable in your code:

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:

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

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:

or disable workbook protection:

Note: You can also protect / unprotect without a password by omitting the Password argument:

Worksheet Protection

Worksheet-level protection prevents changes to individual worksheets.

Protect Worksheet

Unprotect Worksheet

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.

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

Hide Worksheet

Very Hide Worksheet

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.

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
Msgbox ws.name
Next ws Loop Through Selected Sheets Dim ws As Worksheet

For Each ws In ActiveWindow.SelectedSheets
MsgBox ws.Name
Next ws 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
ws.Unprotect «password»
Next ws

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.

Источник

VBA Get Sheet Name / Rename Sheet

In this Article

This tutorial will cover interacting with Sheet names in VBA.

Get Sheet Name

Sheet names are stored in the Name property of the Sheets or Worksheets object. The Sheet Name is the “tab” name that’s visible at the bottom of Excel:

Get ActiveSheet Name

This will display the ActiveSheet name in a message box:

Get Sheet Name by index Number

This will display the first worksheet name in a message box:

This will display the name of the last worksheet in the workbook:

Get Sheet Name by Code Name

In the VBA Editor, there is an option to change the “code name” of a Sheet. The code name is not visible to the Excel user and can only be seen in the VBA Editor:

In VBA, when working with Sheets, you can reference the usual Tab name:

or the VBA code name:

Referencing the code name is desirable in case the Sheet tab name ever changes. If you allow you Excel user access to changing sheet names you should reference the code name in your VBA code so that a Sheet tab name mismatch doesn’t cause an error. Sheet code names are discussed in more detail here.

To get the Sheet name using the VBA Code name, do the following:

Rename Sheet

You can rename Sheets by adjusting the name property of the Sheets or Worksheets object.

Rename ActiveSheet

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!

Rename Sheet by Name

Rename Sheet by Sheet Index Number

Here we use 1 to rename the first Sheet in the Workbook.

Rename Sheet by Code Name

This code will rename a sheet using it’s VBA code name (discussed above):

Check if Sheet Name Exists

The function will return TRUE if the Sheet exists, or FALSE if it does not.

Copy Sheet and Rename

This example is from our article on Copying Sheets.

After copying and pasting a Sheet, the newly created sheet becomes the ActiveSheet. So to rename a copied Sheet, simply use ActiveSheet.Name:

Note: We added error handling to avoid errors if the Sheet name already exists.

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.

Источник

Обращение к рабочим листам Excel из кода VBA. Переименование листов, скрытие и отображение с помощью кода VBA Excel. Свойства Worksheets.Name и Worksheets.Visible.

Обращение к рабочим листам

Рабочий лист (Worksheet) принадлежит коллекции всех рабочих листов (Worksheets) книги Excel. Обратиться к листу можно как к элементу коллекции и, напрямую, по его уникальному имени.

Откройте редактор VBA и обратите внимание на вашу книгу в проводнике, где уникальные имена листов указаны без скобок, а в скобках — имена листов, отображаемые на ярлычках в открытой книге Excel. Уникальные имена листов отсортированы по алфавиту и их расположение по порядку не будет соответствовать их индексам (номерам), если листы перемещались по отношению друг к другу. Индексы листов смотрите по порядку расположения ярлычков в открытой книге. Переместили листы — изменились их индексы.

Обращение к рабочему листу в коде VBA Excel:

‘По уникальному имени

УникИмяЛиста

‘По индексу

Worksheets(N)

‘По имени листа на ярлычке

Worksheets(«Имя листа»)

  • УникИмяЛиста — уникальное имя листа, отображаемое в проводнике редактора VBA без скобок, с помощью кода VBA изменить его невозможно.
  • N — индекс листа от 1 до количества всех листов в книге, соответствует порядковому номеру ярлычка этого листа в открытой книге Excel.
  • Имя листа — имя листа, отображаемое в проводнике редактора VBA в скобках, с помощью кода VBA изменить его можно.

Количество листов в рабочей книге Excel определяется так:

‘В активной книге

Worksheets.Count

‘В любой открытой книге,

‘например, в «Книга1.xlsm»

Workbooks(«Книга1.xlsm»).Worksheets.Count

Переименование листов

В VBA Excel есть некоторые особенности в наименовании листов, так как у рабочего листа есть два свойства, связанных с именем: (Name) и Name. Откройте окно «Properties» в редакторе VBA, нажав клавишу «F4», и выделите любой лист в проводнике. Вы увидите, что в окне «Properties» свойству (Name) в скобках соответствует в проводнике уникальное имя листа без скобок, а свойству Name без скобок соответствует изменяемое имя листа в скобках. Оба имени в окне «Properties» можно редактировать.

С помощью кода VBA Excel можно редактировать только имя листа Name, отображаемое на ярлычке листа и в проводнике без скобок. Для этого используется свойство рабочего листа Worksheets.Name со следующим синтаксисом:

expression.Name

где expression — переменная, представляющая собой объект Worksheet. Смена имени осуществляется путем присвоения нового значения свойству Worksheets.Name.

Допустим, у нас есть лист с уникальным именем (Name) — Лист1, индексом — 1 и именем Name — МойЛист, которое необходимо заменить на имя — Реестр.

Лист1.Name = «Реестр»

Worksheets(1).Name = «Реестр»

Worksheets(«МойЛист»).Name = «Реестр»

Скрытие и отображение листов

Для скрытия и отображения рабочих листов в VBA Excel используется свойство Worksheet.Visible со следующим синтаксисом:

expression.Visible

где expression — переменная, представляющая собой объект Worksheet. Свойству Worksheet.Visible могут присваиваться следующие значения:

  • False — лист становится невидимым, но он будет присутствовать в списке скрытых листов, и пользователь сможет его отобразить с помощью инструментов рабочей книги Excel.
  • xlVeryHidden — лист становится супер невидимым и его не будет в списке скрытых листов, пользователь не сможет его отобразить. Актуально для Excel 2003-2016.
  • True — лист становится видимым.

Аналоги присваиваемых значений:

  • False = xlHidden = xlSheetHidden = 1
  • xlVeryHidden = xlSheetVeryHidden = 2
  • True = xlSheetVisible = -1 (константа xlVisible вызывает ошибку)

Примеры:

Лист1.Visible = xlSheetHidden

Лист2.Visible = 1

Worksheets(Worksheets.Count).Visible = xlVeryHidden

Worksheets(«МойЛист»).Visible = True

Как создать, скопировать, переместить или удалить рабочий лист с помощью кода VBA Excel, смотрите в этой статье.

Понравилась статья? Поделить с друзьями:
  • Vba excel recordset свойства
  • Vba excel sheets by name
  • Vba excel range пример
  • Vba excel range по номерам ячеек
  • Vba excel range количество строк