Sheet names in excel 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.

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

I would like to create an user-defined function in Excel that can return the current worksheet. I could use the

sheetname = ActiveSheet.Name

But the problem with this is, it works and suddenly it starts to get different sheet name. For example, instead of SHEET I LOVE YOU it returns SHEET I HATE YOU.

Is there anyway to fix this — or it might possible because I think it can not be static but varies?

Community's user avatar

asked Oct 11, 2013 at 16:47

user2103670's user avatar

user2103670user2103670

1,59110 gold badges22 silver badges24 bronze badges

0

Function MySheet()

  ' uncomment the below line to make it Volatile
  'Application.Volatile
   MySheet = Application.Caller.Worksheet.Name

End Function

This should be the function you are looking for

sapbucket's user avatar

sapbucket

6,64514 gold badges55 silver badges94 bronze badges

answered Oct 11, 2013 at 17:03

mucio's user avatar

0

This works for me.

worksheetName = ActiveSheet.Name  

answered Oct 17, 2017 at 19:20

moberme's user avatar

mobermemoberme

6597 silver badges13 bronze badges

2

Sub FnGetSheetsName()

    Dim mainworkBook As Workbook

    Set mainworkBook = ActiveWorkbook

    For i = 1 To mainworkBook.Sheets.Count

    'Either we can put all names in an array , here we are printing all the names in Sheet 2

    mainworkBook.Sheets("Sheet2").Range("A" & i) = mainworkBook.Sheets(i).Name

    Next i

End Sub

TylerH's user avatar

TylerH

20.6k64 gold badges76 silver badges97 bronze badges

answered Nov 14, 2015 at 8:22

josef's user avatar

josefjosef

8449 silver badges8 bronze badges

Extend Code for Show Selected Sheet(s) [ one or more sheets].

Sub Show_SelectSheet()
  For Each xSheet In ThisWorkbook.Worksheets
     For Each xSelectSheet In ActiveWindow.SelectedSheets
         If xSheet.Name = xSelectSheet.Name Then
            '=== Show Selected Sheet ===
            GoTo xNext_SelectSheet
         End If
     Next xSelectSheet
  xSheet.Visible = False  
xNext_SelectSheet:
Next xSheet
MsgBox "Show Selected Sheet(s) Completed !!!"
end sub

answered Jun 12, 2019 at 8:36

ChaCha CJ Rune's user avatar

You can use below code to get the Active Sheet name and change it to yours preferred name.

Sub ChangeSheetName()

Dim shName As String
Dim currentName As String
currentName = ActiveSheet.Name
shName = InputBox("What name you want to give for your sheet")
ThisWorkbook.Sheets(currentName).Name = shName

End Sub

answered Oct 24, 2015 at 10:04

Rohit Pal's user avatar

i need to change the sheet name by the name of the file was opened

Sub Get_Data_From_File5()
    Dim FileToOpen As Variant
    Dim OpenBook As Workbook
    Dim currentName As String
    currentName = ActiveSheet.Name
    Application.ScreenUpdating = False
    FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="Excel Files (*.csv*),*csv*")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
        OpenBook.Sheets(1).Range("A1:g5000").Copy
        ThisWorkbook.Worksheets(currentName).Range("Aw1:bc5000").PasteSpecial xlPasteValues
        OpenBook.Close False
       
        
    End If
    Application.ScreenUpdating = True
End Sub

Ian Campbell's user avatar

Ian Campbell

23k14 gold badges35 silver badges57 bronze badges

answered Dec 27, 2020 at 20:37

user14898005's user avatar

Apart from cells and ranges, working with worksheets is another area you should know about to use VBA efficiently in Excel.

Just like any object in VBA, worksheets have different properties and methods associated with it that you can use while automating your work with VBA in Excel.

In this tutorial, I will cover ‘Worksheets’ in detail and also show you some practical examples.

So let’s get started.

All the codes I mention in this tutorial need to be placed in the VB Editor. Go to the ‘Where to Put the VBA Code‘ section to know how it works.

If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.

Difference between Worksheets and Sheets in VBA

In VBA, you have two collections that can be a bit confusing at times.

In a workbook, you can have worksheets and as well as chart sheets. The example below has three worksheets and one chart sheet.

Worksheets Object in Excel VBA - 1 Chart sheet

In Excel VBA:

  • The ‘Worksheets’ collection would refer to the collection of all the worksheet objects in a workbook. In the above example, the Worksheets collection would consist of three worksheets.
  • The ‘Sheets’ collection would refer to all the worksheets as well as chart sheets in the workbook. In the above example, it would have four elements – 3 Worksheets + 1 Chart sheet.

If you have a workbook that only has worksheets and no chart sheets, then ‘Worksheets’ and ‘Sheets’ collection is the same.

But when you have one or more chart sheets, the ‘Sheets’ collection would be bigger than the ‘Worksheets’ collection

Sheets = Worksheets + Chart Sheets

Worksheets Collection Vs Sheets Collection

Now with this distinction, I recommend being as specific as possible when writing a VBA code.

So if you have to refer to worksheets only, use the ‘Worksheets’ collection, and if you have to refer to all sheets (including chart sheets), the use the ‘Sheets’ collection.

In this tutorial, I will be using the ‘Worksheets’ collection only.

Referencing a Worksheet in VBA

There are many different ways you can use to refer to a worksheet in VBA.

Understanding how to refer to worksheets would help you write better code, especially when you’re using loops in your VBA code.

Using the Worksheet Name

The easiest way to refer to a worksheet is to use its name.

For example, suppose you have a workbook with three worksheets – Sheet 1, Sheet 2, Sheet 3.

And you want to activate Sheet 2.

You can do that using the following code:

Sub ActivateSheet()
Worksheets("Sheet2").Activate
End Sub

The above code asks VBA to refer to Sheet2 in the Worksheets collection and activate it.

Since we are using the exact sheet name, you can also use the Sheets collection here. So the below code would also do that same thing.

Sub ActivateSheet()
Sheets("Sheet2").Activate
End Sub

Using the Index Number

While using the sheet name is an easy way to refer to a worksheet, sometimes, you may not know the exact name of the worksheet.

For example, if you’re using a VBA code to add a new worksheet to the workbook, and you don’t know how many worksheets are already there, you would not know the name of the new worksheet.

In this case, you can use the index number of the worksheets.

Suppose you have the following sheets in a workbook:

Worksheets Object in Excel VBA - 1 Chart sheet

The below code would activate Sheet2:

Sub ActivateSheet()
Worksheets(2).Activate
End Sub

Note that we have used index number 2 in Worksheets(2). This would refer to the second object in the collection of the worksheets.

Now, what happens when you use 3 as the index number?

It will select Sheet3.

If you’re wondering why it selected Sheet3, as it’s clearly the fourth object.

This happens because a chart sheet is not a part of the worksheets collection.

So when we use the index numbers in the Worksheets collection, it will only refer to the worksheets in the workbook (and ignore the chart sheets).Index Numbers in Worksheets Collection in VBA

On the contrary, if you’re using Sheets, Sheets(1) would refer to Sheets1, Sheets(2) would refer to Sheet2, Sheets(3) would refer to Chart1 and Sheets(4) would refer to Sheet3.

This technique of using index number is useful when you want to loop through all the worksheets in a workbook. You can count the number of worksheets and then loop through these using this count (we will see how to do this later in this tutorial).

Note: The index number goes from left to right. So if you shift Sheet2 to the left of Sheet1, then Worksheets(1) would refer to Sheet2.

Using the Worksheet Code Name

One of the drawbacks of using the sheet name (as we saw in the section above) is that a user can change it.

And if the sheet name has been changed, your code wouldn’t work until you change the name of the worksheet in the VBA code as well.

To tackle this problem, you can use the code name of the worksheet (instead of the regular name that we have been using so far). A code name can be assigned in the VB Editor and doesn’t change when you change the name of the sheet from the worksheet area.

To give your worksheet a code name, follow the below steps:

  1. Click the Developer tab.
  2. Click the Visual Basic button. This will open the VB Editor.Visual Basic button in the Developer tab
  3. Click the View option in the menu and click on Project Window. This will make the Properties pane visible. If the Properties pane is already visible, skip this step.
  4. Click on the sheet name in the project explorer that you want to rename.
  5. In the Properties pane, change the name in the field in front of (Name). Note that you can’t have spaces in the name.CodeName of the Worksheet in VBA

The above steps would change the name of your Worksheet in the VBA backend. In the Excel worksheet view, you can name the worksheet whatever you want, but in the backend, it will respond to both the names – the sheet name and the code name.

Worksheets Object in Excel VBA - Code name vs sheet name

In the above image, the sheet name is ‘SheetName’ and the code name is ‘CodeName’. Even if you change the sheet name on the worksheet, the code name still remains the same.

Now, you can use either the Worksheets collection to refer to the worksheet or use the codename.

For example, both the line will activate the worksheet.

Worksheets("Sheetname").Activate
CodeName.Activate

The difference in these two is that if you change the name of the worksheet, the first one wouldn’t work. But the second line would continue to work even with the changed name. The second line (using the CodeName) is also shorter and easier to use.

Referring to a Worksheet in a Different Workbook

If you want to refer to a worksheet in a different workbook, that workbook needs to be open while the code runs, and you need to specify the name of the workbook and the worksheet that you want to refer to.

For example, if you have a workbook with the name Examples and you want to activate Sheet1 in the Example workbook, you need to use the below code:

Sub SheetActivate()
Workbooks("Examples.xlsx").Worksheets("Sheet1").Activate
End Sub

Note that if the workbook has been saved, you need to use the file name along with the extension. If you’re not sure what name to use, take help from Project Explorer.

Worksheets Object in Excel VBA - file name in project explorer

In case the workbook has not been saved, you don’t need to use the file extension.

Adding a Worksheet

The below code would add a worksheet (as the first worksheet – i.e., as the leftmost sheet in the sheet tab).

Sub AddSheet()
Worksheets.Add
End Sub

It takes the default name Sheet2 (or any other number based on how many sheets are already there).

If you want a worksheet to be added before a specific worksheet (say Sheet2), then you can use the below code.

Sub AddSheet()
Worksheets.Add Before:=Worksheets("Sheet2")
End Sub

The above code tells VBA to add a sheet and then uses the ‘Before’ statement to specify the worksheet before which the new worksheet should to be inserted.

Similarly, you can also add a sheet after a worksheet (say Sheet2), using the below code:

Sub AddSheet()
Worksheets.Add After:=Worksheets("Sheet2")
End Sub

If you want the new sheet to be added to the end of the sheets, you need to first know how many sheets are there. The following code first counts the number of sheets, and the adds the new sheet after the last sheet (to which we refer using the index number).

Sub AddSheet()
Dim SheetCount As Integer
SheetCount = Worksheets.Count
Worksheets.Add After:=Worksheets(SheetCount)
End Sub

Deleting a Worksheet

The below code would delete the active sheet from the workbook.

Sub DeleteSheet()
ActiveSheet.Delete
End Sub

The above code would show a warning prompt before deleting the worksheet.

Worksheets Object in Excel VBA - warning prompt

If you don’t want to see the warning prompt, use the below code:

Sub DeleteSheet()
Application.DisplayAlerts = False
ActiveSheet.Delete
Application.DisplayAlerts = True
End Sub

When Application.DisplayAlerts is set to False, it will not show you the warning prompt. If you use it, remember to set it back to True at the end of the code.

Remember that you can’t undo this delete, so use the above code when you’re absolutely sure.

If you want to delete a specific sheet, you can do that using the following code:

Sub DeleteSheet()
Worksheets("Sheet2").Delete
End Sub

You can also use the code name of the sheet to delete it.

Sub DeleteSheet()
Sheet5.Delete
End Sub

Renaming the Worksheets

You can modify the name property of the Worksheet to change its name.

The following code will change the name of Sheet1 to ‘Summary’.

Sub RenameSheet()
Worksheets("Sheet1").Name = "Summary"
End Sub

You can combine this with the adding sheet method to have a set of sheets with specific names.

For example, if you want to insert four sheets with the name 2018 Q1, 2018 Q2, 2018 Q3, and 2018 Q4, you can use the below code.

Sub RenameSheet()
Dim Countsheets As Integer
Countsheets = Worksheets.Count
For i = 1 To 4
Worksheets.Add after:=Worksheets(Countsheets + i - 1)
Worksheets(Countsheets + i).Name = "2018 Q" & i
Next i
End Sub

In the above code, we first count the number of sheets and then use a For Next loop to insert new sheets at the end. As the sheet is added, the code also renames it.

Assigning Worksheet Object to a Variable

When working with worksheets, you can assign a worksheet to an object variable, and then use the variable instead of the worksheet references.

For example, if you want to add a year prefix to all the worksheets, instead of counting the sheets and the running the loop that many numbers of times, you can use the object variable.

Here is the code that will add 2018 as a prefix to all the worksheet’s names.

Sub RenameSheet()
Dim Ws As Worksheet
For Each Ws In Worksheets
Ws.Name = "2018 - " & Ws.Name
Next Ws
End Sub

The above code declares a variable Ws as the worksheet type (using the line ‘Dim Ws As Worksheet’).

Now, we don’t need to count the number of sheets to loop through these. Instead, we can use ‘For each Ws in Worksheets’ loop. This will allow us to go through all the sheets in the worksheets collection. It doesn’t matter whether there are 2 sheets or 20 sheets.

While the above code allows us to loop through all the sheets, you can also assign a specific sheet to a variable.

In the below code, we assign the variable Ws to Sheet2 and use it to access all of Sheet2’s properties.

Sub RenameSheet()
Dim Ws As Worksheet
Set Ws = Worksheets("Sheet2")
Ws.Name = "Summary"
Ws.Protect
End Sub

Once you set a worksheet reference to an object variable (using the SET statement), that object can be used instead of the worksheet reference. This can be helpful when you have a long complicated code and you want to change the reference. Instead of making the change everywhere, you can simply make the change in the SET statement.

Note that the code declares the Ws object as the Worksheet type variable (using the line Dim Ws as Worksheet).

Hide Worksheets Using VBA (Hidden + Very Hidden)

Hiding and Unhiding worksheets in Excel is a straightforward task.

You can hide a worksheet and the user would not see it when he/she opens the workbook. However, they can easily unhide the worksheet by right-clicking on any sheet tab.

Worksheets Object in Excel VBA - unhide right-click macro

But what if you don’t want them to be able to unhide the worksheet(s).

You can do this using VBA.

The code below would hide all the worksheets in the workbook (except the active sheet), such that you can not unhide it by right-clicking on the sheet name.

Sub HideAllExcetActiveSheet()
Dim Ws As Worksheet
For Each Ws In ThisWorkbook.Worksheets
If Ws.Name <> ActiveSheet.Name Then Ws.Visible = xlSheetVeryHidden
Next Ws
End Sub

In the above code, the Ws.Visible property is changed to xlSheetVeryHidden.

  • When the Visible property is set to xlSheetVisible, the sheet is visible in the worksheet area (as worksheet tabs).
  • When the Visible property is set to xlSheetHidden, the sheet is hidden but the user can unhide it by right-clicking on any sheet tab.
  • When the Visible property is set to xlSheetVeryHidden, the sheet is hidden and cannot be unhidden from worksheet area. You need to use a VBA code or the properties window to unhide it.

If you want to simply hide sheets, that can be unhidden easily, use the below code:

Sub HideAllExceptActiveSheet()
Dim Ws As Worksheet
For Each Ws In ThisWorkbook.Worksheets
If Ws.Name <> ActiveSheet.Name Then Ws.Visible = xlSheetHidden
Next Ws
End Sub

The below code would unhide all the worksheets (both hidden and very hidden).

Sub UnhideAllWoksheets()
Dim Ws As Worksheet
For Each Ws In ThisWorkbook.Worksheets
Ws.Visible = xlSheetVisible
Next Ws
End Sub
Related Article: Unhide All Sheets In Excel (at one go)

Hide Sheets Based on the Text in it

Suppose you have multiple sheets with the name of different departments or years and you want to hide all the sheets except the ones that have the year 2018 in it.

You can do this using a VBA INSTR function.

The below code would hide all the sheets except the ones with the text 2018 in it.

Sub HideWithMatchingText()
Dim Ws As Worksheet
For Each Ws In Worksheets
If InStr(1, Ws.Name, "2018", vbBinaryCompare) = 0 Then
Ws.Visible = xlSheetHidden
End If
Next Ws
End Sub

In the above code, the INSTR function returns the position of the character where it finds the matching string. If it doesn’t find the matching string, it returns 0.

The above code checks whether the name has the text 2018 in it. If it does, nothing happens, else the worksheet is hidden.

You can take this a step further by having the text in a cell and using that cell in the code. This will allow you to have a value in the cell and then when you run the macro, all the sheets, except the one with the matching text in it, would remain visible (along with the sheets where you’re entering the value in the cell).

Sorting the Worksheets in an Alphabetical Order

Using VBA, you can quickly sort the worksheets based on their names.

For example, if you have a workbook that has sheets for different department or years, then you can use the below code to quickly sort these sheets in an ascending order.

Sub SortSheetsTabName()
Application.ScreenUpdating = False
Dim ShCount As Integer, i As Integer, j As Integer
ShCount = Sheets.Count
For i = 1 To ShCount - 1
For j = i + 1 To ShCount
If Sheets(j).Name < Sheets(i).Name Then
Sheets(j).Move before:=Sheets(i)
End If
Next j
Next i
Application.ScreenUpdating = True
End Sub

Note that this code works well with text names and in most of the cases with years and numbers too. But it can give you the wrong results in case you have the sheet names as 1,2,11. It will sort and give you the sequence 1, 11, 2. This is because it does the comparison as text and considers 2 bigger than 11.

Protect/Unprotect All the Sheets at One Go

If you have a lot of worksheets in a workbook and you want to protect all the sheets, you can use the VBA code below.

It allows you to specify the password within the code. You will need this password to unprotect the worksheet.

Sub ProtectAllSheets()
Dim ws As Worksheet
Dim password As String
password = "Test123" 'replace Test123 with the password you want
For Each ws In Worksheets
ws.Protect password:=password
Next ws
End Sub

The following code would unprotect all the sheets in one go.

Sub ProtectAllSheets()
Dim ws As Worksheet
Dim password As String
password = "Test123" 'replace Test123 with the password you used while protecting
For Each ws In Worksheets
ws.Unprotect password:=password
Next ws
End Sub

Creating a Table of Contents of All Worksheets (with Hyperlinks)

If you have a set of worksheets in the workbook and you want to quickly insert a summary sheet which has the links to all the sheets, you can use the below code.

Sub AddIndexSheet()
Worksheets.Add
ActiveSheet.Name = "Index"
For i = 2 To Worksheets.Count
ActiveSheet.Hyperlinks.Add Anchor:=Cells(i - 1, 1), _
Address:="", SubAddress:=Worksheets(i).Name & "!A1", _
TextToDisplay:=Worksheets(i).Name
Next i
End Sub

The above code inserts a new worksheet and names it Index.

It then loops through all the worksheets and creates a hyperlink for all the worksheets in the Index sheet.

Where to Put the VBA Code

Wondering where the VBA code goes in your Excel workbook?

Excel has a VBA backend called the VBA editor. You need to copy and paste the code into the VB Editor module code window.

Here are the steps to do this:

  1. Go to the Developer tab.IF Then Else in Excel VBA - Developer Tab in ribbon
  2. Click on the Visual Basic option. This will open the VB editor in the backend.Click on Visual Basic
  3. In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
  4. Go to Insert and click on Module. This will insert a module object for your workbook.VBA Loops - inserting module
  5. Copy and paste the code in the module window.VBA Loops - inserting module

You May Also Like the Following Excel VBA Tutorials:

  • Working with Workbooks using VBA.
  • Using IF Then Else Statements in VBA.
  • For Next Loop in VBA.
  • Creating a User-Defined Function in Excel.
  • How to Record a Macro in Excel.
  • How to Run a Macro in Excel.
  • Excel VBA Events – An Easy (and Complete) Guide.
  • How to Create an Add-in in Excel.
  • How to Save and Reuse Macro using Excel Personal Macro Workbook.
  • Using Active Cell in VBA in Excel (Examples)
  • How to Open Excel Files Using VBA (Examples)
Image: Aajan Getty Images/iStockphoto

Whether your Microsoft Excel workbook has three sheets or 50, knowing what you have is important. Some complex applications require detailed documentation that includes sheet names. For those times when a quick look isn’t good enough, and you must have a list, you have a couple of options: You can go the manual route, which would be tedious and need updating every time you made a change. Or you can run a quick VBA procedure. In this article, I’ll show you easily modified code that generates a list of sheet names and hyperlinks. There are other ways to generate a list, but I prefer the VBA method because it’s automated and easy to modify to suit individual requirements.

SEE: 69 Excel tips every user should master (TechRepublic)

I’m using Microsoft 365 on a Windows 10 64-bit system, but you can use earlier versions. To save time, download the .xlsx, .xls and .cls files. Macros aren’t supported by the online version. This article assumes you have basic Excel skills and are familiar with VBA, but even a beginner should be able to follow the instructions to success.

How to enter and run code in VBA

If you’re new to VBA code, you might be wondering about the terms procedure and macro. You’ll see them used interchangeably when VBA is the language used. This isn’t true for all languages. In VBA, both a procedure and a macro are a named set of instructions that are preformed when called. Some developers refer to a sub procedure as a macro and a function procedure as a procedure because a procedure can accept arguments. Many use the term macro for everything. Some, like me, tend to use the term procedure for everything. Furthermore, Access has a macro feature that is separate from any VBA code. Don’t get too hung up on the terms.

SEE: Windows 10: Lists of vocal commands for speech recognition and dictation (free PDF) (TechRepublic)

To enter VBA code, press Alt + F11 to open the Visual Basic Editor. In the Project Explorer to the left, choose ThisWorkbook and enter the code. If you’re using a ribbon version, you must save the file as a macro-enabled file to use macros. You can also import the downloadable .cls file that contains the code. Or, you can work with either of the downloadable Excel workbooks. If you’re entering the code yourself, please don’t copy it from this web page. Instead, enter it manually or copy it to a text editor and then paste that code into a module.

When in the VBE, press F5 to run a procedure, but be sure to click inside the procedure you want to run. When in an Excel sheet, click the Developer tab, click Macros in the Code group, choose the procedure in the resulting dialog shown in Figure A, and then click Run.

Figure A

The bare bones VBA code

A simple list of sheet names is easy to generate using VBA thanks to the Worksheets collection. Listing A shows a simple For Each loop that cycles through this collection. For each sheet, the code uses the Name property to enter that name in column A, beginning at A1, in Sheet1.

Listing A

Sub ListSheetNames()

‘List all sheet names in column A of Sheet1.

‘Update to change location of list.

Sheets(“Sheet1”).Activate

ActiveSheet.Cells(1, 1).Select

‘Generate a list of hyperlinks to each sheet in workbook in Sheet1.

For Each sh In Worksheets

ActiveCell = sh.Name

ActiveCell.Offset(1, 0).Select ‘Move down a row.

Next

End Sub

When adapting this code, you might want to change the location of the list; do so by changing the first two lines accordingly. The For Each loop also offers possibilities for modifying. You might want to add header names or values to number the sheet names.

This code will list hidden and very hidden sheets, which you might not want. When that’s the case, you’ll need to check the Visible properties xlSheetVisible and xlSheetVeryHidden. In addition, because we’re actively selecting A1 on Sheet1, the cursor moves to that location. If you don’t want the active cell to change, use implicit selection statements. To learn more about implicit and explicit references, read Excel tips: How to select cells and ranges efficiently using VBA.

There are many modifications you might want to make. For example, instead of an ordinary list of text, you might want a list of hyperlinks.

How to generate a list of hyperlinks in Excel

It’s not unusual for a complex workbook to include a list of hyperlinks to each sheet in the workbook. The procedure you’ll use, shown in Listing B, is similar to Listing A, but this code uses the Name property to create a hyperlink.

Listing B

Sub ListSheetNamesAsHyperlinks()

‘Generate list of hyperlinks to each sheet in workbook in Sheet1, A1.

Sheets(“Sheet1”).Activate

ActiveSheet.Cells(1, 1).Select

‘Generate a list of hyperlinks to each sheet in workbook in Sheet1.

For Each sh In Worksheets

ActiveSheet.Hyperlinks.Add Anchor:=Selection, _

Address:=””, SubAddress:=”‘” &amp; sh.Name &amp; “‘” &amp; “!A1”, _

TextToDisplay:=sh.Name

ActiveCell.Offset(1, 0).Select ‘Moves down a row

Next

End Sub

The first two lines select cell A1 in Sheet1. Update these two statements to relocate the list. The For Each loop cycles through all the sheets, using the Name property to create a hyperlink for each sheet.

The Hyperlinks.Add property in the For Each uses the form

.Add Anchor, Address, [SubAddress], [ScreenTip], [TextToDisplay]

The parameter information is listed below:

  • Anchor: A Range or Shape object.
  • Address: The address of the hyperlink.
  • SubAddress: The subaddress of the hyperlink
  • ScreenTip: Information displayed when the mouse pointer pauses over the hyperlink.
  • TextToDisplay: The hyperlink text.

Our procedure’s SubAddress argument

SubAddress:=”‘” &amp; sh.Name &amp; “‘” &amp; “!A1”

builds a string using the current sheet’s name and the cell reference A1. For instance, if the current sheet is Sheet1, this evaluates to ‘Sheet1’!A1. Subsequently, when you click this hyperlink, it takes you to cell A1 on Sheet1. As before, you can easily modify this procedure to reflect the way you want to use this list.

Both sub procedures are easy to use. Both can be easily modified to change the list’s position or to add more information to the simple list.

If you have an Excel workbook that has hundreds of worksheets, and now you want to get a list of all the worksheet names, you can refer to this article. Here we will share 3 simple methods with you.

Sometimes, you may be required to generate a list of all worksheet names in an Excel workbook. If there are only few sheets, you can just use the Method 1 to list the sheet names manually. However, in the case that the Excel workbook contains a great number of worksheets, you had better use the latter 2 methods, which are much more efficient.

Method 1: Get List Manually

  1. First off, open the specific Excel workbook.
  2. Then, double click on a sheet’s name in sheet list at the bottom.
  3. Next, press “Ctrl + C” to copy the name.Copy Sheet Name
  4. Later, create a text file.
  5. Then, press “Ctrl + V” to paste the sheet name.Paste Sheet Name
  6. Now, in this way, you can copy each sheet’s name to the text file one by one.

Method 2: List with Formula

  1. At the outset, turn to “Formulas” tab and click the “Name Manager” button.
  2. Next, in popup window, click “New”.Name Manager
  3. In the subsequent dialog box, enter “ListSheets” in the “Name” field.
  4. Later, in the “Refers to” field, input the following formula:
=REPLACE(GET.WORKBOOK(1),1,FIND("]",GET.WORKBOOK(1)),"")

Customize New Name

  1. After that, click “OK” and “Close” to save this formula.
  2. Next, create a new worksheet in the current workbook.
  3. Then, enter “1” in Cell A1 and “2” in Cell A2.
  4. Afterwards, select the two cells and drag them down to input 2,3,4,5, etc. in Column A.Enter Sequential Numbers
  5. Later, put the following formula in Cell B1.
=INDEX(ListSheets,A1)

Enter Formula in Cell B1

  1. At once, the first sheet name will be input in Cell B1.
  2. Finally, just copy the formula down until you see the “#REF!” error.Copy Formula Down to List Sheet Names

Method 3: List via Excel VBA

  1. For a start, trigger Excel VBA editor according to “How to Run VBA Code in Your Excel“.
  2. Then, put the following code into a module or project.
Sub ListSheetNamesInNewWorkbook()
    Dim objNewWorkbook As Workbook
    Dim objNewWorksheet As Worksheet

    Set objNewWorkbook = Excel.Application.Workbooks.Add
    Set objNewWorksheet = objNewWorkbook.Sheets(1)

    For i = 1 To ThisWorkbook.Sheets.Count
        objNewWorksheet.Cells(i, 1) = i
        objNewWorksheet.Cells(i, 2) = ThisWorkbook.Sheets(i).Name
    Next i

    With objNewWorksheet
         .Rows(1).Insert
         .Cells(1, 1) = "INDEX"
         .Cells(1, 1).Font.Bold = True
         .Cells(1, 2) = "NAME"
         .Cells(1, 2).Font.Bold = True
         .Columns("A:B").AutoFit
    End With
End Sub

VBA Code - List Sheet Names

  1. Later, press “F5” to run this macro right now.
  2. At once, a new Excel workbook will show up, in which you can see the list of worksheet names of the source Excel workbook.Listed Sheet Names in New Excel Workbook

Comparison

Advantages Disadvantages
Method 1 Easy to operate Too troublesome if there are a lot of worksheets
Method 2 Easy to operate Demands you to type the index first
Method 3 Quick and convenient Users should beware of the external malicious macros
Easy even for VBA newbies

Excel Gets Corrupted

MS Excel is known to crash from time to time, thereby damaging the current files on saving. Therefore, it’s highly recommended to get hold of an external powerful Excel repair tool, such as DataNumen Outlook Repair. It’s because that self-recovery feature in Excel is proven to fail frequently.

Author Introduction:

Shirley Zhang is a data recovery expert in DataNumen, Inc., which is the world leader in data recovery technologies, including sql fix and outlook repair software products. For more information visit www.datanumen.com

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:
  • Sheet linking in excel
  • Short vowels word families
  • Sheet function in excel
  • Short two word phrases
  • Sheet cell value excel