Excel vba this worksheet name

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

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.

Содержание

  1. Worksheet object (Excel)
  2. Remarks
  3. Example
  4. Events
  5. Methods
  6. Properties
  7. See also
  8. Support and feedback
  9. VBA Name Worksheet
  10. Excel VBA Name WorkSheet
  11. Examples to Name Worksheet using VBA
  12. Example #1
  13. Example #2
  14. Things to Remember
  15. Recommended Articles
  16. VBA Get Sheet Name / Rename Sheet
  17. Get Sheet Name
  18. Get ActiveSheet Name
  19. Get Sheet Name by index Number
  20. Get Sheet Name by Code Name
  21. Rename Sheet
  22. Rename ActiveSheet
  23. VBA Coding Made Easy
  24. Rename Sheet by Name
  25. Rename Sheet by Sheet Index Number
  26. Rename Sheet by Code Name
  27. Check if Sheet Name Exists
  28. Copy Sheet and Rename
  29. VBA Code Examples Add-in
  30. Reference excel worksheet by name?
  31. 3 Answers 3
  32. Объект Worksheet (Excel)
  33. Замечания
  34. Пример
  35. События
  36. Методы
  37. Свойства
  38. См. также
  39. Поддержка и обратная связь

Worksheet object (Excel)

Represents a worksheet.

The Worksheet object is a member of the Worksheets collection. The Worksheets collection contains all the Worksheet objects in a workbook.

The Worksheet object is also a member of the Sheets collection. The Sheets collection contains all the sheets in the workbook (both chart sheets and worksheets).

Example

Use Worksheets (index), where index is the worksheet index number or name, to return a single Worksheet object. The following example hides worksheet one in the active workbook.

The worksheet index number denotes the position of the worksheet on the workbook’s tab bar. Worksheets(1) is the first (leftmost) worksheet in the workbook, and Worksheets(Worksheets.Count) is the last one. All worksheets are included in the index count, even if they are hidden.

The worksheet name is shown on the tab for the worksheet. Use the Name property to set or return the worksheet name. The following example protects the scenarios on Sheet1.

When a worksheet is the active sheet, you can use the ActiveSheet property to refer to it. The following example uses the Activate method to activate Sheet1, sets the page orientation to landscape mode, and then prints the worksheet.

This example uses the BeforeDoubleClick event to open a specified set of files in Notepad. To use this example, your worksheet must contain the following data:

  • Cell A1 must contain the names of the files to open, each separated by a comma and a space.
  • Cell D1 must contain the path to where the Notepad files are located.
  • Cell D2 must contain the path to where the Notepad program is located.
  • Cell D3 must contain the file extension, without the period, for the Notepad files (txt).

When you double-click cell A1, the files specified in cell A1 are opened in Notepad.

Events

Methods

Properties

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

VBA Name Worksheet

Excel VBA Name WorkSheet

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

After mentioning the sheet name, we need to select the “Name” property to change the worksheet 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.

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

Examples to Name Worksheet using VBA

Example #1

Change or Rename Sheet using Variables.

Look at the below sample code.

Code:

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

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

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

Important Note to Remember

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.

For example, look at the below image.

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:

Now, copy this code to your module.

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

Like this, using the “NAME” property of the worksheet in VBA Worksheet In VBA Excel 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: –

Источник

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.

Источник

Reference excel worksheet by name?

I have the name of a worksheet stored as a string in a variable. How do I perform some operation on this worksheet?

I though I would do something like this:

How do I get this done?

3 Answers 3

There are several options, including using the method you demonstrate, With, and using a variable.

My preference is option 4 below: Dim a variable of type Worksheet and store the worksheet and call the methods on the variable or pass it to functions, however any of the options work.

The best way is to create a variable of type Worksheet , assign the worksheet and use it every time the VBA would implicitly use the ActiveSheet .

This will help you avoid bugs that will eventually show up when your program grows in size.

For example something like Range(«A1:C10»).Sort Key1:=Range(«A2») is good when the macro works only on one sheet. But you will eventually expand your macro to work with several sheets, find out that this doesn’t work, adjust it to ShTest1.Range(«A1:C10»).Sort Key1:=Range(«A2») . and find out that it still doesn’t work.

Here is the correct way:

To expand on Ryan’s answer, when you are declaring variables (using Dim) you can cheat a little bit by using the predictive text feature in the VBE, as in the image below.

If it shows up in that list, then you can assign an object of that type to a variable. So not just a Worksheet, as Ryan pointed out, but also a Chart, Range, Workbook, Series and on and on.

You set that variable equal to the object you want to manipulate and then you can call methods, pass it to functions, etc, just like Ryan pointed out for this example. You might run into a couple snags when it comes to collections vs objects (Chart or Charts, Range or Ranges, etc) but with trial and error you’ll get it for sure.

Источник

Объект Worksheet (Excel)

Замечания

Объект Worksheet является членом коллекции Worksheets . Коллекция Worksheets содержит все объекты Worksheet в книге.

Объект Worksheet также является членом коллекции Sheets . Коллекция Листов содержит все листы книги (как листы диаграмм, так и листы).

Пример

Используйте worksheets (index), где index — это номер или имя индекса листа, чтобы вернуть один объект Worksheet . В следующем примере лист скрыт в активной книге.

Номер индекса листа обозначает положение листа на панели вкладок книги. Worksheets(1) — это первый (самый левый) лист в книге, а Worksheets(Worksheets.Count) — последний. Все листы включаются в число индексов, даже если они скрыты.

Имя листа отображается на вкладке листа. Используйте свойство Name , чтобы задать или вернуть имя листа. В следующем примере выполняется защита сценариев на Листе 1.

Если лист является активным листом, можно использовать свойство ActiveSheet , чтобы ссылаться на него. В следующем примере используется метод Activate для активации Sheet1, задает ориентацию страницы в альбомный режим, а затем выводит лист.

В этом примере событие BeforeDoubleClick используется для открытия указанного набора файлов в Блокноте. Чтобы использовать этот пример, лист должен содержать следующие данные:

  • Ячейка A1 должна содержать имена файлов для открытия, разделенные запятой и пробелом.
  • Ячейка D1 должна содержать путь к расположению файлов Блокнота.
  • Ячейка D2 должна содержать путь к расположению программы Блокнота.
  • Ячейка D3 должна содержать расширение файла без точки для файлов Блокнота (txt).

При двойном щелчке ячейки A1 файлы, указанные в ячейке A1, открываются в Блокноте.

События

Методы

Свойства

См. также

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

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?

VBA Name Worksheet

Excel VBA Name Worksheet

This is one of the easiest tasks to do. Changing the worksheet name in VBA can be done manually and automatically and both the ways are easy. Sometimes we may need to change the worksheet name just to process and continue some work. Excel VBA Name Worksheet can be the requirement of some process work where we need to change the name of Worksheet after the task is completed or just to differentiate between some worked on the sheet we could also use VBA Name Worksheet to automate this process.

There are many different ways to change the name of any worksheet. But the simplest and easiest way to do it as shown below.

Line of Code

Where in the above-shown line of code, NAME = Property in VBA, which is used when we want to use the worksheet name in any manner.

How to Change Name of Worksheet in Excel VBA?

We will learn how to change the name of a worksheet in Excel by using the VBA Code.

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

VBA Name Worksheet – Example #1

Let’s see a simple example where we will change the name of any worksheet. For this, follow the below steps:

Step 1: Open a Module from Insert menu tab firstly as shown below.

Insert Module

Step 2: Write the subprocedure of the VBA Name Sheet. We can choose any name to define the module VBA Code.

Code:

Sub VBA_NameWS1()

End Sub

VBA Name Worksheet Example 1-1

Step 3: Define a variable for Worksheet function in any name as shown below. Better use the name which shows or represents that variable.

Code:

Sub VBA_NameWS1()

Dim NameWS As Worksheet

End Sub

VBA Name Worksheet Example 1-2

Step 4: Now use that variable and set that with Worksheet name which we want to change as shown below.

Code:

Sub VBA_NameWS1()

Dim NameWS As Worksheet
Set NameWS = Worksheets("Sheet1")

End Sub

VBA Name Worksheet Example 1-3

Step 5: Now use Name function with a variable which we defined and choose a new name which we want to give the selected sheet. Here, our sheet is Sheet1 and the new name is New Sheet.

Code:

Sub VBA_NameWS1()

Dim NameWS As Worksheet
Set NameWS = Worksheets("Sheet1")
NameWS.Name = "New Sheet"

End Sub

New Sheet Example 1-4

Step 6: Before we run the code, let’s just see the name of sheets down there.

VBA Name Worksheet Example 1-5

Step 7: Now Run the code by clicking on the Play button located below the menu bar.

VBA Name Worksheet Example 1-6

Step 8: We will see the name of the sheet will get changed to New Sheet from Sheet1.

VBA Name Worksheet Example 1-7

VBA Name Worksheet – Example #2

There is another way to change the name of any worksheet using VBA. This is also as easy as shown in example-1. We add a new worksheet and change the name of that worksheet. For this, follow the below steps:

Step 1: Write the subprocedure of the VBA name worksheet in any suitable name as shown below.

Code:

Sub VBA_NameWS2()

End Sub

VBA Name Worksheet Example 2-1

Step 2: To add a new worksheet, we will use the Worksheets command along with Add function.

Code:

Sub VBA_NameWS2()

Worksheets.Add

End Sub

Add function Example 2-2

Step 3: Now to change the name of the added worksheet, we will use the above line of code and with the help of Name function insert a new name. Here, we have considered New Sheet1 as a new name.

Code:

Sub VBA_NameWS2()

Worksheets. Add
Worksheets.Add.Name = "New Sheet1"

End Sub

VBA Name Worksheet Example 2-3

Step 4: Now run the code by pressing the F5 key. We 0will see, a new worksheet will be added apart from the sheets which we have seen in example-1, in the name of New Sheet1 as shown below.

New Sheet1 Example 2-4

VBA Name Worksheet – Example #3

There is another way to perform this activity. In this example, we will do VBA Name Worksheet with the help of For-Next Loop. We will create a loop to see how many worksheets are there in the current workbook with their names. For this, follow the below steps:

Step 1: Write the subprocedure for VBA Name Worksheet as shown below.

Code:

Sub VBA_NameWS3()

End Sub

VBA Name Worksheet Example 3-1

Step 2: Open a For loop in which we will start the count the worksheet names from the 1st position till the Worksheet are there in the current workbook.

Code:

Sub VBA_NameWS3()

For A = 1 To ThisWorkbook.Sheets.Count

End Sub

For loop Example 3-2

Step 3: Now to see the names of worksheets we will use MsgBox to carry current WorkBook sheet names as shown below.

Code:

Sub VBA_NameWS3()

For A = 1 To ThisWorkbook.Sheets.Count
MsgBox ThisWorkbook.Sheets(A).Name

End Sub

WorkBook sheet Example 3-3

Step 4: Close the loop with Next as shown below.

Code:

Sub VBA_NameWS3()

For A = 1 To ThisWorkbook.Sheets.Count
MsgBox ThisWorkbook.Sheets(A).Name
Next

End Sub

VBA Name Worksheet Example 3-4

Step 5: Before we run the code, let’s have a look at the sheet names which we have as shown below.

VBA Name Worksheet Example 3-5

Step 6: Now it is expected that we would get these names in the message box, so we will run this code. We will see different message box is now carrying the names of all the sheet names that we have in sequence as shown below.

VBA Name Worksheet 3-6

Pros and Cons of VBA Name Worksheet

  • This makes easy to change the name of any worksheet when we have to automate the full process.
  • We can even check the names of any or all the worksheets even though they are hidden.
  • Although it is an automated way of using the worksheet names it does not give much impact on improvement unless the code size is huge.

Things to Remember

  • Above shown steps can be compressed more into 1 line of code.
  • Save the workbook in macro enable excel format to preserve the written VBA code.
  • VBA has named as property.
  • We can many types of tasks such as changing the name of the worksheet to extracting the name of the worksheet to adding a sheet and then naming it.
  • If there is any mismatch in the name of the worksheet which we supply then we will end up with getting an error message as Subscript out of range.

Recommended Articles

This is a guide to VBA Name Worksheet. Here we discuss how to change the name of worksheets in Excel using VBA code along with practical examples and downloadable excel templates. You can also go through our other suggested articles –

  1. VBA Delete Sheet
  2. VBA IF Statements
  3. VBA Unprotect Sheet
  4. VBA While Loop

Like this post? Please share to your friends:
  • Excel vba worksheet hidden
  • Excel vba this workbook save
  • Excel vba workbooks методы
  • Excel vba workbooks worksheets
  • Excel vba this workbook open