Excel vba if worksheet name is not

VBA Code to Check if Sheet with Name exists?

This Excel vba code will check if sheet with a specific name exists in the workbook.

As per Microsoft specifications, You can add as many number of sheets depending on the limits of Your computer’s memory.

So, this loop will check if any of those sheets has the name passed as parameter to this function.

  • There are 2 methods presented in this page.
  • Use option 1 first & Test the performance.
  • If the loop is taking more time, then use 2nd option.

VBA function to Check if Sheet Exists

Here is the vba code the loop thru all the sheets & verifies the name passed as parameter.

Public Function SheetExists(SheetName As String) As Boolean
    'Declare variables - Officetricks.com
    Dim wSh As Worksheet
    Dim bReturnValue As Boolean
    
    'Loop Thru Each Sheet in workbook
    bReturnValue = False
    For Each wSh In ThisWorkbook.Sheets
    
        'Check whether there is a name match
        If VBA.UCase(wSh.Name) = VBA.UCase(SheetName) Then
            bReturnValue = True
            Exit For
        End If
    Next wSh
    
    'Return Match Result
    SheetExists = bReturnValue
End Function

The above function will return ‘True’ if the sheet with exact name exists in the workbook. Otherwise it will return false.

Lets see another version that is more faster than the above one.

VBA Worksheet Exists with specific Name in Workbook

This function does not loop thru all existing sheet. It directly checks for the Sheet name.

If you face any issue in using this function, then use the first one. Option 1 gives good results consistently.

Public Function fSheetExists(SheetName As String) As Boolean
    'Declare variables - Officetricks.com
    Dim wSh As Worksheet
    Dim bReturnValue As Boolean
    Set wSh = Nothing
    
    'Assign Sheet to Object
    On Error Resume Next
    Set wSh = ThisWorkbook.Sheets(SheetName)
    On Error GoTo 0
    
    'Check if Sheet with name exists
    If wSh Is Nothing Then
        bReturnValue = False
    Else
        bReturnValue = True
    End If
    
    'Return Match Result
    fSheetExists = bReturnValue
End Function

Using this function You can confirm is a sheet exists of not.

Then by using the function in here, you can create or add new worksheet to workbook & rename it. Click here to get the code to add new sheet & rename it.

  • Remove From My Forums
  • Question

  • I’m trying to figure out, using VBA, to check to see if a Worksheet.Name exists before hiding columns.  strRangeName1 is a String variable representing a range name in the sht.Names collection.  Does anyone know why this code doesn’t
    work?  Also if it did work, would it error out if the strRangeName1 = «»?

    My VBA Code:

    If Not sht.Names(strRangeName1) Is Nothing Then

      sht.Names(RangeName1)Columns.EntireColumn.Hidden = True

    Else

      ‘Do nothing.

    End IF

    Thanks,

    ….bob sutor

    • Edited by

      Wednesday, March 20, 2013 5:21 AM
      correction

Answers

  • >>Can anyone tell me why this line of code doesn’t work:

    >If Not sht.Names(strRangeName1) Is Nothing Then

    It errors because the range object doesn’t exist.  There is a difference between a range object that exists but has not been assigned to a range (dimmed but not Set to anything for example) and a range object that doesn’t exist.

    This is a function I use to test whether a local name exists on a sheet:

    »Returns True if Nm is defined locally on sheet WS.
    Function LocalNameExists(WS As Worksheet, Nm As String) As Boolean
        Dim Temp As String
        On Error Resume Next
        Err.Clear
        Temp = WS.Names(Nm).Value
        LocalNameExists = (Err.Number = 0)
    End Function

    • Marked as answer by
      ConstPM
      Wednesday, March 20, 2013 6:08 PM

This tutorial explains how to use Excel VBA Custom Function to check if worksheet exists, and add new worksheet if worksheet doesn’t exist

Sometimes we want to manipulate worksheet in a workbook but we are not sure if the worksheet exists. For example, we want to add a worksheet, if it already exists, skip the adding worksheet code.

VBA code – Custom Function to check if worksheet exists

There are many Functions on the internet that do the same job. The below custom Function is the shortest possible version modified by me, I believe it should be the most efficient version.

Function wsExists(wksName As String) As Boolean
    On Error Resume Next
    wsExists = Len(Worksheets(wksName).Name)
    On Error GoTo 0
End Function

Explanation of VBA code – Custom Function to check if worksheet exists

Step 1: Worksheets(wksName).Name – Return the name of wksName if the worksheet exists, otherwise it would return an error “Run-time error ‘9’: Subscript out of range”

worksheet_exists

Step 2: Len(Worksheets(wksName).Name – Return a number which is the length of the worksheet name if worksheet exists, otherwise continue to return error

Although the above code return a number and an error, the Boolean Function can return TRUE FALSE (when Excel does not have a normal choice for TRUE and FALSE, number is regarded as TRUE, ERROR is regarded as FALSE), but you need to use On Error Resume Next statement because the error would cause the code to stop running.

Syntax – Custom Function to check if worksheet exists

wsExists(wksName)

wksName is the worksheet name in Text

This Function returns TRUE and FALSE

Example – Custom Function to check if worksheet exists

The below code adds “worksheet1” if worksheet doesn’t exist.

Sub createWS()
    If Not wsExists("worksheet1") Then
         Set newWS = ThisWorkbook.Worksheets.Add(After:=Worksheets("Sheet8"))
         newWS.Name = "worksheet1"
     End If
End Sub
Function wsExists(wksName As String) As Boolean
    On Error Resume Next
    wsExists = Len(Worksheets(wksName).Name)
    On Error GoTo 0
End Function

If you plan to delete and recreate a new worksheet anyway, then

Public Sub createWS()
    On Error Resume Next 
        Application.DisplayAlerts = False
        Sheets("worksheet1").Delete
        Application.DisplayAlerts = True
    On Error GoTo 0        
        Set newWs = ActiveWorkbook.Worksheets.Add
        newWs.Name = "worksheet1"
End Sub

Outbound References

http://www.excelforum.com/excel-programming-vba-macros/488529-check-if-a-worksheet-exists.html

There could be a time when you have to check if a worksheet, which you have create or deleted in a workbook in a VBA macro / code, exists. We can do this easily using a function / macro. There are multiple ways of checking if a worksheet exists.

We will cover the following ways in this article:

1. User Defined Function known as UDF
2. Sub routine through message box

First option: User Defined Function

Following snapshot contains few sheets names & we will check if the names of sheet in column A exist.

img1

To find if a specific sheet exists, we need to follow the below steps to launch VB editor

  • Click on Developer tab
  • From Code group select Visual Basic

img2

  • Copy the below code in the standard module
Option Explicit

Function WorksheetExists(ByVal WorksheetName As String) As Boolean
Dim Sht As Worksheet

    For Each Sht In ThisWorkbook.Worksheets
        If Application.Proper(Sht.Name) = Application.Proper(WorksheetName) Then
            WorksheetExists = True
            Exit Function
        End If
    Next Sht
WorksheetExists = False
End Function

img3

  • In order to check, we will use UDF in cell B2 as
  • =WorksheetExists(A2)

img4

  • In the above image, “MasterSheet” does not exist in our sample workbook; hence, formula has given answer as False

Code Explanation:

This function takes the value for “WorksheetName” from the macro which performs other activities. If you need to change it as per your code, you may.

For Each Sht In ThisWorkbook.Worksheets and Next Sht are the starting and ending parts of the loop respectively.

Then If Application.Proper(Sht.Name) = Application.Proper(WorksheetName) Then

            WorksheetExists = True

Checks if the Sheet name is matching the Sheet name passed from the main macro. If it does, WorksheetExists is True, and we can exit the function. Otherwise, WorksheetExists = False is returned back to the main macro. The loop goes from the 1st sheet to the next until all the sheets have been checked.

Second Option: Sub routine through message box

We can have a normal subroutine which is calling a UDF and, if the specified sheet is found, the message box will display, ‘sheet exist’; if not found, then msgbox pops up, ‘sheet not found’.

To check, we will copy the following code in the standard module:

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

img5

After running the macro “FindSheet”, we will get the following message box if sheet exists:

img6

If Sheet does not exist we will get the following message box:

img7

Similarly, we can have a simple IF loop which checks if the sheet exists and performs certain actions thereafter.

Sub test()
Dim ws As Worksheet
    For Each ws In ThisWorkbook.Worksheets
         If ws.Name <> "Main" Then
            ws.Range("A1").Value = ws.Name
        Else
            ws.Range("A1").Value = "MAIN LOGIN PAGE"
        End If
    Next ws
End Sub

img8

  • To test the above macro, we need to create a sheet name “Main”. This macro is very simple
  • It loops through each worksheet in the workbook
  • Then it checks if the worksheet name is not MAIN
  • If it is MAIN, it displays text, like “MAIN LOGIN PAGE” in A1 of that sheet, else it displays the name of the sheet in cell A1

img9

  • This is just another way of checking if the sheet exists. If it exists, perform action A, if not, action B

Conclusion: We can identify whether a sheet exists in our workbook or not; we can use UDF or subroutine as per our convenience.

image 48

If you liked our blogs, share it with your friends on Facebook. And also you can follow us on Twitter and Facebook.

We would love to hear from you, do let us know how we can improve, complement or innovate our work and make it better for you. Write us at info@exceltip.com

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.

  • #2

Hi

If you are going to overwrite them anyway, Just use this:

Application.DisplayAlerts = False
On Error Resume Next
Sheets(«NewShtL»).Delete
Sheets(«NewShtB»).Delete
Application.DisplayAlerts = True
On Error GoTo 0
Sheets.Add().Name = «NewSht»

But to check if sheet exists you would use

Dim wsSheet As Worksheet
On Error Resume Next
Set wsSheet = Sheets(«NewShtL»)
On Error GoTo 0
If Not wsSheet Is Nothing Then
MsgBox «I do exist»
Else
MsgBox «I do NOT exist»
End If

  • #3

Hi. The following code is using Loop.
Please try. Regards,

Sub Test()
Dim sh As Worksheet, flg As Boolean
For Each sh In Worksheets
If sh.Name Like «NewSht*» Then flg = True: Exit For
Next
If flg = True Then
MsgBox «Found!»
Else
Sheets.Add.Name = «NewSht»
End If
End Sub

  • #4

very clever.

setting the non-existent sheet as an object and then blowing through the errors is clever indeed.

also learned from the use of wildcard * in the second suggestion.

  • #5

Public Function WorksheetExists(ByVal WorksheetName As String) As Boolean

On Error Resume Next
WorksheetExists = (Sheets(WorksheetName).Name <> «»)
On Error GoTo 0

End Function

Last edited: Jun 16, 2009

  • #6

I am having problems implementing the code to check whether a sheet already exists in my own macro — for some reason, the following code always seems to think that the new sheet name already exists, and asks whether I would like to overwrite it, even when the sheet in question patently does not exist. Below is a section of the macro, containing the relevant code:

Code:

Sub NewSheets()
Dim agent As String
Dim lastone As String
Dim i As Integer
Dim max As Integer
Dim ws As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
max = InputBox("How Many Rows down the list do you wish to use?", "Enter a number to create that number of sheets")
For i = 1 To max
    'for the first of the new sheets, the previous sheet is called template, by definition
    If i = 1 Then
            lastone = "Template"
    'otherwise, the last previous sheet name will be one higher in the list than the current
    Else
            lastone = Worksheets("Lists").Range("A1").Offset(i - 1, 0).Value
    End If
        'get the agent name
        agent = Worksheets("Lists").Range("A1").Offset(i, 0).Value
        'check whether a sheet with that name already exists
        On Error Resume Next
        Set ws = Sheets(agent)
    'if none with that name, create a new sheet
    If ws Is Nothing Then
            ActiveWorkbook.Sheets("Template").Copy after:=ActiveWorkbook.Sheets(lastone)
            ActiveSheet.Name = agent
    'if the sheet already exists, ask whether the user wants to replace it
    Else
            overW = MsgBox("This sheet already exists - Overwrite?", vbYesNoCancel, agent)
        If overW = vbYes Then
                Sheets(agent).Delete
                ActiveWorkbook.Sheets("Template").Copy after:=ActiveWorkbook.Sheets(lastone)
                ActiveSheet.Name = agent
        ElseIf overW = vbNo Then
                GoTo Skip
        ElseIf overW = vbCancel Then
                Exit Sub
        End If
    End If

I cannot work out which part I have got wrong — can anyone help?

Thanks for looking at the post, and all replies are much appreciated!

  • #7

Possibly you have not reset ws as nothing:

Code:

        On Error Resume Next
        Set ws = Sheets(agent)

Try amending to:

Code:

        [COLOR="Blue"]Set ws = Nothing[/COLOR]
        On Error Resume Next
        Set ws = Sheets(agent)

Also not that error handling will be left «on» and may mask other problems now. So also preferable is:

Code:

        Set ws = Nothing
        On Error Resume Next
        Set ws = Sheets(agent)
        [COLOR="Blue"]On Error GoTo 0[/COLOR]

  • #8

Thanks

Thanks — worked perfectly. I will look up what «on error goto 0» actually does and thus try to avoid that in the future.

  • #9

Hey Guys,

I saw this thread and I wanted to show the code I came up with.

I don’t like «On Error Resume Next» command so I made the following function:

Code:

Sub Testing()
    Dim SheetName1, SheetName2 As String
    Dim Result As Boolean
    Dim i As Long
    
    
    SheetName = Array("laskgfasdfalskg", "Config")
    
    For i = 0 To UBound(SheetName)
        Result = WorksheetExists(SheetName(i))
        If Result = False Then
            MsgBox "Sheet name " & SheetName(i) & " doesn't exist!"
        Else
            MsgBox "Sheet name " & SheetName(i) & " does exist!"
        End If
    Next i
    
    
End Sub



Public Function WorksheetExists(ByVal WorksheetName As String) As Boolean
    
    Dim Sht As Worksheet
        
    WorksheetExists = False
        
    For Each Sht In ActiveWorkbook.Worksheets
        If Sht.Name = WorksheetName Then worksheetexits = True
    Next Sht
    
End Function

  • #10

Here is a working version

Function WorksheetExists(ByVal WorksheetName As String) As Boolean
Dim Sht As Worksheet
For Each Sht In ThisWorkbook.Worksheets
If Application.Proper(Sht.Name) = Application.Proper(WorksheetName) Then
WorksheetExists = True
Exit Function
End If
Next Sht
WorksheetExists = False
End Function

Like this post? Please share to your friends:
  • Excel vba if workbook opened
  • Excel vba if with multiple or
  • Excel vba if variable is error
  • Excel vba if value is text
  • Excel vba if value is integer