Как присвоить имя листу в excel vba

Обращение к рабочим листам 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, смотрите в этой статье.

Home / VBA / How to RENAME a Sheet using VBA in Excel

When you add a new sheet in a workbook, you have the option to name it. But you can also rename it any time using the name property of the worksheet. In this tutorial, we will look at different ways to rename a sheet or multiple sheets using a VBA code.

Steps to Rename a Sheet using a VBA Code

  1. First, define the sheet that you want to rename using the worksheet object.
  2. After that, you need to use (.Name) to access the name property that you want to change.
  3. Next, type an equal sign to that to tell VBA the value you want to use to rename the sheet.
  4. In the end, type the name of the sheet that you want to use.

Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook

Rename the Activesheet

If you want to rename the active sheet, in that case, you don’t need to define the sheet name, instead, you need to use the ActiveSheet object that tells VBA to refer to the sheet that is active right now. Here’s the code.

Activesheet.Name = "mySheet"

Note: To rename a sheet you don’t need to activate it.

As you know every sheet has a number based on its position in the workbook. Let’s say you want to rename the sheet that you have on the fifth number, the code would be.

Sheets(5).Name = "mySheet5"

When you run the above macro, it renames the sheet that is on the fifth number.

Check if Sheet Exists before Renaming

If you try to rename a worksheet that doesn’t exist, VBA will show you an error, just like below.

The solution to this problem is the following code that uses FOR EACH, which can loop through all the worksheets to find the sheet that you have defined and then rename that sheet.

Sub check_sheet_rename()
Dim ws As Worksheet
Dim mySheet As String
Dim SheetName As String

mySheet = InputBox("enter the name of the sheet that you want to rename.")
SheetName = InputBox("Enter new name for the sheet.")

For Each ws In ThisWorkbook.Worksheets
    If mySheet = ws.Name Then
    ws.Name = SheetName
    End If
Next ws

End Sub

Rename a Sheet using Value from a Cell or a Range

You can also rename a sheet by taking value from a cell. Let’s say the value is in cell A1.

Sheets("Sheet1").name = Range("A1").Value

But let’s say you want to name multiple sheets based on the values in a range of cells. In that case, you need to have code like the following.

Sub vba_sheet_rename_multiple()
Dim wsCount As Long
Dim rCount As Long
Dim ws As Worksheet
Dim name As Range
Dim i As Long

wsCount = ThisWorkbook.Worksheets.Count
rCount = Range("A1:A10").Rows.Count

'Checks if the count of the names provided is less _
or more than the sheets in the workbook
If wsCount <> rCount Then
    MsgBox "There's some problem with the names provided."
    Exit Sub
Else

    'Check if any of the cells in the name range is empty.
    For Each name In Range("A1:A10")
        If IsEmpty(name) = True Then
            i = i + 1
        End If
    Next name
    If i > 0 Then
        MsgBox "There's is a blank cell in the names range."
        Exit Sub
    End If
End If

'rename each sheet using the value from the range cell by cell.
i = 1

For Each ws In ThisWorkbook.Worksheets
    ws.name = Range("A1:A10").Cells(i, 1).Value
    i = 1 + i
Next ws

End Sub

When you run this VBA code, first it will check if the cells in the range are equal to the number of sheets that you have in the workbook. After that, it will check if all the cells in the range that you have specified have values or not. And in the end, rename all the sheets using those names.

It will verify two conditions using IF THEN ELSE and then rename all the sheets.

More Tutorials on VBA Worksheets

  • Back to VBA Worksheet / VBA Tutorial

 

Юрий М, Спасибо огромное! то, чего не доставало самостоятельно нашел на других форумах благодаря знакомым уже пользователям (Ikki), итак мой кусок кода теперь выглядит сл. образом (для информации другим гостям этого форума):

Код
Set WBA = ThisWorkbook
    Set WS1 = ActiveSheet
    Set WS2 = Choose(Right(WS1.CodeName, 2), _
    Month_01, _
    Month_02, _
    Month_03, _
    Month_04, _
    Month_05, _
    Month_06, _
    Month_07, _
    Month_08, _
    Month_09, _
    Month_10, _
    Month_11, _
    Month_12)

само-собой это лишь малая часть кода, но теперь можно переименовывать листы в книге пользователям без опаски сбить код, обновленный код протестил, работает как часики.
Hugo, тоже огромное спасибо, но я еще «очень новичок» в VBA, и многого еще не понимаю и не знаю, но желание разбираться есть, так что разбираться буду. Не совсем понял в вашем коде, что и куда, как дойду знаниями до нужного уровня разберусь )). Быть может я не совсем ясно задачу поставил, суть в том что (на примере того же декабря) у меня в «АО 12» собраны и отсортированы из общей базы («12») нужные мне данные в зависимости от той недели за которую я составляю отчет, но не все данные для работы кода есть на данном листе, чтобы излишне не грузить книгу формулами (вес ее увеличивается с каждой формулой) мне проще часть данных взять с активного листа («АО 12»), а недостающие данные взять с исходного листа соответствующего месяца («12») и потом все это перенести в другую книгу-шаблон отчета именно поэтому я и хотел присвоить переменной WS1 свойства и методы активного листа, а WS2 ориентируясь на два последних знака активного листа определить нужный мне месяц и также присвоить все свойства и методы, чтобы обращаться уже к переменным а не к листам в коде.. Мне остается потом уже в автоматически сохраненном отчете в нужное мне место и с нужным мне именем добавить немного данных с внутренней программы и все, то что раньше я копипастил вручную с двух листов, распределял где профильное где общее в течение часа, теперь у меня делается автоматически в течение нескольких секунд и корректируется еще в течение 5-10 минут. ))) Чего-то я отвлекся… В общем спасибо всем за помощь! Не раз уже убеждался что форум полезный, спасибо и создателю этого сайта!

In this guide, we’re going to show you how to create and name a worksheet with VBA in Excel.

Download Workbook

Syntax

You can create and name a worksheet using the Sheets.Add and Worksheets.Add methods. Both methods work similarly and have 4 optional arguments and return a sheet object which can take a Name property.

Sheets.Add ([Before], [After], [Count], [Type])

Worksheets.Add ([Before], [After], [Count], [Type])

Name Description
Before Optional. The sheet before which the new sheet is to be added.
If omitted, Excel creates the new sheet(s) before the selected sheet(s).
After Optional. The sheet after which the new sheet is added.
If omitted, Excel creates the new sheet(s) before the selected sheet(s).
Count The number of sheets to be added.
The default is the number of selected sheets.
Type Specifies the sheet type.
The default is xlWorksheet which represents a standard worksheet.

Adding a single sheet

All arguments are optional. The method without arguments creates worksheet(s) equal to the number of selected worksheets before the first selected worksheet.

Sheets.Add

For example, if two sheets are selected, the method will add two worksheets. To ignore the selected sheets and set the sheet number to one (1), use 1 for the Count argument.

Sheets.Add Count:=1

Adding multiple sheets

You can set the Count argument to an integer greater than 1 to add multiple sheets at once. For example, the following code adds three (3) worksheets.

Sheets.Add Count:=3

Adding a sheet with a name

Sheets.Add method returns a sheet object and sets its name by updating the Name property. A property is an attribute of object that determines one of the object’s characteristics. The property of an object is addressed by entering the property name after the corresponding object and a dot(.). Just like calling the Add method for the Sheets object.

If all you need is to create worksheets and name them regardless of their position, use one of the following code lines.

Sheets.Add.Name = “My Sheet”
Sheets.Add(Count:=1).Name = “My Sheet” ‘Use this line to ensure creating a single sheet

Adding a sheet before or after a specific sheet

If the new sheet’s position is important, use either the Before or After argument. Each argument accepts a sheet object. The new sheet will be created before or after the sheet you supplied based on the argument you are using.

You can call a sheet object by giving the sheet’s name or index to Sheets or Worksheets objects. It can be a variable which you have defined. Here are some examples:

Sheets.Add Before:=Worksheets("My Sheet") ‘Add sheet(s) before “My Sheet”
Sheets.Add After:=Worksheets(3) ‘Add sheet(s) after the third sheet
Dim ws As Worksheet ‘Define a new worksheet object
Set ws = Sheets.Add ‘Create and assign new sheet to the worksheet object
Sheets.Add After:=ws ‘Add a new sheet after the recently added sheet (ws)

Creating and naming multiple worksheets

To name multiple worksheets, you have to use an array of names and a loop. Let’s say you have names in a range like A1:A5 in the worksheet named “Sheet1”. A loop should check each cell inside the range and create a worksheet from the corresponding name. Check out the following code:

 Sub CreateAndNameMultipleSheets()
    Dim rng As Range 'Range object which defines a cell
    For Each rng In Sheets("Sheet1").Range("A1:A5")
        Sheets.Add.Name = rng.Value
    Next
End Sub

This is our last tip for how to create and name a worksheet with VBA in Excel article. If you are new to loops in VBA, check out All You Need to Know on How to Create a VBA loop in Excel to understand and find more ways of looping.

I have some very simple code that adds a new Worksheet, after the current worksheets, to an Excel document, and then changes its name to one entered in a text box on a userform. Works fine on a new workbook, however in a workbook that has a number of existing worksheets it creates the new worksheet, but does not rename it.

This only happens the first time you run this code, the next time it will run fine. The thing that makes it even stranger is that if you open the VBA editor to try and debug it, it then runs fine as well. This obviously makes finding the error pretty hard.

The code I’m using is here:

     Dim WS As Worksheet

     Set WS = Sheets.Add(After:=Sheets(Worksheets.count))
     WS.name = txtSheetName.value

Pretty simple. I’m wondering if this problem is that it is trying to rename the sheet before it is properly created? Is there a better way to write this code?

Update:
I’ve started debugging this using msgboxes, as opening the debugger makes the problem stop, and it seems that it just stops processing the code halfway through:

  Dim WS As Worksheet
  MsgBox (WS Is Nothing)

    Set WS = Sheets.Add(After:=Sheets(Worksheets.count))
    '***** Nothing after this point gets processed *******
    MsgBox (WS Is Nothing)
    MsgBox WS.name

    WS.name = txtSheetName.value
    MsgBox WS.name

Понравилась статья? Поделить с друзьями:
  • Как присвоить имя диапазону ячеек excel
  • Как присвоить имя диапазона excel
  • Как присвоить имя диаграмме в excel
  • Как присвоить имя данным в excel
  • Как присвоить имя в excel 2010