Vba excel check if sheet exist

Dim wkbkdestination As Workbook
Dim destsheet As Worksheet

For Each ThisWorkSheet In wkbkorigin.Worksheets 
    'this throws subscript out of range if there is not a sheet in the destination 
    'workbook that has the same name as the current sheet in the origin workbook.
    Set destsheet = wkbkdestination.Worksheets(ThisWorkSheet.Name) 
Next

Basically I loop through all sheets in the origin workbook then set destsheet in the destination workbook to the sheet with the same name as the currently iterated one in the origin workbook.

How can I test if that sheet exists? Something like:

If wkbkdestination.Worksheets(ThisWorkSheet.Name) Then 

BigBen's user avatar

BigBen

43.9k6 gold badges27 silver badges40 bronze badges

asked Jul 14, 2011 at 3:23

yse's user avatar

1

Some folk dislike this approach because of an «inappropriate» use of error handling, but I think it’s considered acceptable in VBA… An alternative approach is to loop though all the sheets until you find a match.

Function WorksheetExists(shtName As String, Optional wb As Workbook) As Boolean
    Dim sht As Worksheet

    If wb Is Nothing Then Set wb = ThisWorkbook
    On Error Resume Next
    Set sht = wb.Sheets(shtName)
    On Error GoTo 0
    WorksheetExists = Not sht Is Nothing
End Function

darcyy's user avatar

darcyy

5,2165 gold badges27 silver badges41 bronze badges

answered Jul 14, 2011 at 4:27

Tim Williams's user avatar

Tim WilliamsTim Williams

150k8 gold badges96 silver badges124 bronze badges

14

If you are specifically interested in worksheets only, you can use a simple Evaluate call:

Function WorksheetExists(sName As String) As Boolean
    WorksheetExists = Evaluate("ISREF('" & sName & "'!A1)")
End Function

answered Feb 12, 2015 at 9:25

Rory's user avatar

RoryRory

32.4k5 gold badges31 silver badges34 bronze badges

10

You don’t need error handling in order to accomplish this. All you have to do is iterate over all of the Worksheets and check if the specified name exists:

Dim exists As Boolean

For i = 1 To Worksheets.Count
    If Worksheets(i).Name = "MySheet" Then
        exists = True
    End If
Next i

If Not exists Then
    Worksheets.Add.Name = "MySheet"
End If

ke1v3y's user avatar

answered Mar 27, 2013 at 20:21

fbonetti's user avatar

fbonettifbonetti

6,5823 gold badges33 silver badges32 bronze badges

1

I wrote this one:

Function sheetExist(sSheet As String) As Boolean
On Error Resume Next
sheetExist = (ActiveWorkbook.Sheets(sSheet).Index > 0)
End Function

answered Apr 16, 2018 at 19:24

AOBR's user avatar

AOBRAOBR

2792 silver badges4 bronze badges

3

As checking for members of a collection is a general problem, here is an abstracted version of @Tim’s answer:

Function Contains(objCollection As Object, strName as String) As Boolean
    Dim o as Object
    On Error Resume Next
    set o = objCollection(strName)
    Contains = (Err.Number = 0)
    Err.Clear
 End Function

This function can be used with any collection like object (Shapes, Range, Names, Workbooks, etc.).

To check for the existence of a sheet, use If Contains(Sheets, "SheetName") ...

shA.t's user avatar

shA.t

16.4k5 gold badges53 silver badges111 bronze badges

answered Jan 24, 2013 at 20:11

Peter Albert's user avatar

Peter AlbertPeter Albert

16.8k4 gold badges66 silver badges88 bronze badges

2

Corrected:
Without error-handling:

Function CheckIfSheetExists(SheetName As String) As Boolean
      CheckIfSheetExists = False
      For Each WS In Worksheets
        If SheetName = WS.name Then
          CheckIfSheetExists = True
          Exit Function
        End If
      Next WS
End Function

answered Feb 17, 2015 at 14:07

Shai Alon's user avatar

Shai AlonShai Alon

95013 silver badges20 bronze badges

0

In case anyone wants to avoid VBA and test if a worksheet exists purely within a cell formula, it is possible using the ISREF and INDIRECT functions:

=ISREF(INDIRECT("SheetName!A1"))

This will return TRUE if the workbook contains a sheet called SheetName and FALSE otherwise.

answered Jan 7, 2016 at 6:33

VirtualMichael's user avatar

Compact wsExists function (without reliance on Error Handling!)

Here’s a short & simple function that doesn’t rely on error handling to determine whether a worksheet exists (and is properly declared to work in any situation!)

Function wsExists(wsName As String) As Boolean
    Dim ws: For Each ws In Sheets
    wsExists = (wsName = ws.Name): If wsExists Then Exit Function
    Next ws
End Function

Example Usage:

The following example adds a new worksheet named myNewSheet, if it doesn’t already exist:

If Not wsExists("myNewSheet") Then Sheets.Add.Name = "myNewSheet"

More Information:

  • MSDN : For EachNext Statement (VBA)
  • MSDN : Exit Statement (VBA)
  • MSDN : Comparison Operators (VBA)

answered May 11, 2018 at 16:56

ashleedawg's user avatar

ashleedawgashleedawg

20k8 gold badges73 silver badges104 bronze badges

My solution looks much like Tims but also works in case of non-worksheet sheets — charts

Public Function SheetExists(strSheetName As String, Optional wbWorkbook As Workbook) As Boolean
    If wbWorkbook Is Nothing Then Set wbWorkbook = ActiveWorkbook 'or ThisWorkbook - whichever appropriate
    Dim obj As Object
    On Error GoTo HandleError
    Set obj = wbWorkbook.Sheets(strSheetName)
    SheetExists = True
    Exit Function
HandleError:
    SheetExists = False
End Function

.

answered Aug 3, 2014 at 15:43

uildriks's user avatar

uildriksuildriks

511 silver badge1 bronze badge

Many years late, but I just needed to do this and didn’t like any of the solutions posted… So I made one up, all thanks to the magic of (SpongeBob rainbow hands gesture) «Evaluate()»!

Evaluate("IsError(" & vSheetName & "!1:1)")

Returns TRUE if Sheet does NOT exist; FALSE if sheet DOES exist.
You can substitute whatever range you like for «1:1», but I advise against using a single cell, cuz if it contains an error (eg, #N/A), it will return True.

answered Aug 1, 2016 at 16:37

X37V's user avatar

1

Short and clean:

Function IsSheet(n$) As Boolean
    IsSheet = Not IsError(Evaluate("'" & n & "'!a1"))
End Function

Roy Latham's user avatar

answered Apr 3, 2020 at 4:13

Excel Hero's user avatar

Excel HeroExcel Hero

14.1k4 gold badges31 silver badges39 bronze badges

0

Put the test in a function and you will be able to reuse it and you have better code readability.

Do NOT use the «On Error Resume Next» since it may conflict with other part of your code.

Sub DoesTheSheetExists()
    If SheetExist("SheetName") Then
        Debug.Print "The Sheet Exists"
    Else
        Debug.Print "The Sheet Does NOT Exists"
    End If
End Sub

Function SheetExist(strSheetName As String) As Boolean
    Dim i As Integer

    For i = 1 To Worksheets.Count
        If Worksheets(i).Name = strSheetName Then
            SheetExist = True
            Exit Function
        End If
    Next i
End Function

answered Jan 9, 2014 at 9:26

Martin Carlsson's user avatar

Martin CarlssonMartin Carlsson

4512 gold badges6 silver badges17 bronze badges

Public Function WorkSheetExists(ByVal strName As String) As Boolean
   On Error Resume Next
   WorkSheetExists = Not Worksheets(strName) Is Nothing
End Function

sub test_sheet()

 If Not WorkSheetExists("SheetName") Then
 MsgBox "Not available"
Else MsgBox "Available"
End If

End Sub

answered Aug 5, 2013 at 10:56

M1NT's user avatar

M1NTM1NT

3861 gold badge4 silver badges13 bronze badges

Why not just use a small loop to determine whether the named worksheet exists? Say if you were looking for a Worksheet named «Sheet1» in the currently opened workbook.

Dim wb as Workbook
Dim ws as Worksheet

Set wb = ActiveWorkbook

For Each ws in wb.Worksheets

    if ws.Name = "Sheet1" then
        'Do something here
    End if

Next

answered Jan 16, 2015 at 7:55

ScottMcC's user avatar

ScottMcCScottMcC

3,9441 gold badge27 silver badges35 bronze badges

    For Each Sheet In Worksheets
    If UCase(Sheet.Name) = "TEMP" Then
    'Your Code when the match is True
        Application.DisplayAlerts = False
        Sheet.Delete
        Application.DisplayAlerts = True
    '-----------------------------------
    End If
Next Sheet

answered Mar 28, 2017 at 12:24

Shrikant's user avatar

ShrikantShrikant

5234 silver badges15 bronze badges

If you are a fan of WorksheetFunction. or you work from a non-English country with a non-English Excel this is a good solution, that works:

WorksheetFunction.IsErr(Evaluate("'" & wsName & "'!A1"))

Or in a function like this:

Function WorksheetExists(sName As String) As Boolean
    WorksheetExists = Not WorksheetFunction.IsErr(Evaluate("'" & sName & "'!A1"))
End Function

answered May 23, 2017 at 9:25

Vityata's user avatar

VityataVityata

42.4k8 gold badges55 silver badges98 bronze badges

Change «Data» to whatever sheet name you’re testing for…

On Error Resume Next 

Set DataSheet = Sheets("Data")

If DataSheet Is Nothing Then

     Sheets.Add(after:=ActiveSheet).Name = "Data"
     ''or whatever alternate code you want to execute''
End If

On Error GoTo 0

Dan Lowe's user avatar

Dan Lowe

49.9k19 gold badges123 silver badges111 bronze badges

answered Jul 10, 2017 at 16:54

gth826a's user avatar

gth826agth826a

1011 silver badge4 bronze badges

Without any doubt that the above function can work, I just ended up with the following code which works pretty well:

Sub Sheet_exist ()
On Error Resume Next
If Sheets("" & Range("Sheet_Name") & "") Is Nothing Then
    MsgBox "doesnt exist"
Else
    MsgBox "exist"
End if
End sub

Note: Sheets_Name is where I ask the user to input the name, so this might not be the same for you.

Cody Gray's user avatar

Cody Gray

237k50 gold badges488 silver badges570 bronze badges

answered Jun 28, 2016 at 2:24

MAx Segura's user avatar

I did another thing: delete a sheet only if it’s exists — not to get an error if it doesn’t:

Excel.DisplayAlerts = False 
Dim WS
For Each WS In Excel.Worksheets
    If WS.name = "Sheet2" Then
        Excel.sheets("Sheet2").Delete
        Exit For
    End If
Next
Excel.DisplayAlerts = True

answered Feb 17, 2015 at 15:22

Shai Alon's user avatar

Shai AlonShai Alon

95013 silver badges20 bronze badges

I use this function to check and return a new sheet name if needed. WSname is the desired worksheet name and WBCur is the workbook you would like to check in. I use this because there is no need for error handling and can call it whenever i am creating a new worksheet.

Public Function CheckNewWorksheetName(WSName As String, WBCur As Workbook) 'Will return New Name if needed
    Dim NewWSNum As Long, A As Integer, B As Integer, WorksheetFound As Boolean
    NewWSNum = 1
    WorksheetFound = False
    For A = 1 To WBCur.Worksheets.Count
        If WBCur.Worksheets(A).Name = WSName Then
            A = WBCur.Worksheets.Count
            WorksheetFound = True
        End If
    Next A
    
    If WorksheetFound = False Then
        CheckNewWorksheetName = WSName
    Else
        Do While WorksheetFound = True
            WorksheetFound = False
            For B = 1 To WBCur.Worksheets.Count
                If WBCur.Worksheets(B).Name = WSName & "_" & NewWSNum Then
                    B = WBCur.Worksheets.Count
                    WorksheetFound = True
                    NewWSNum = NewWSNum + 1
                End If
            Next B
        Loop
        CheckNewWorksheetName = WSName & "_" & NewWSNum
    End If
End Function

answered Jul 14, 2021 at 19:51

Alex Johnson's user avatar

I came up with an easy way to do it, but I didn’t create a new sub for it. Instead, I just «ran a check» within the sub I was working on. Assuming the sheet name we’re looking for is «Sheet_Exist» and we just want to activate it if found:

Dim SheetCounter As Integer

SheetCounter = 1

Do Until Sheets(SheetCounter).Name = "Sheet_Exist" Or SheetCounter = Sheets.Count + 1
 SheetCounter = SheetCounter +1
Loop
If SheetCounter < Sheets.Count + 1 Then
 Sheets("Sheet_Exist").Activate
Else
 MsgBox("Worksheet ""Sheet_Exist"" was NOT found")
End If

I also added a pop-up for when the sheet doesn’t exist.

answered Jun 14, 2018 at 15:13

imjordy23's user avatar

I know it is an old post, but here is another simple solution that is fast.

Public Function worksheetExists(ByVal wb As Workbook, ByVal sheetNameStr As String) As Boolean

On Error Resume Next
worksheetExists = (wb.Worksheets(sheetNameStr).Name <> "")
Err.Clear: On Error GoTo 0

End Function

answered Apr 4, 2019 at 15:39

Guest's user avatar

GuestGuest

4302 silver badges4 bronze badges

I actually had a simple way to check if the sheet exists and then execute some instruction:

In my case I wanted to delete the sheet and then recreated the same sheet with the same name but the code was interrupted if the program was not able to delete the sheet as it was already deleted

Sub Foo ()

    Application.DisplayAlerts = False

    On Error GoTo instructions
    Sheets("NAME OF THE SHEET").Delete

    instructions:

    Sheets.Add After:=Sheets(Sheets.Count)
    ActiveSheet.Name = "NAME OF THE SHEET"

End Sub

Cody Gray's user avatar

Cody Gray

237k50 gold badges488 silver badges570 bronze badges

answered Mar 7, 2014 at 14:47

chenaou's user avatar

1

If you want to create a sheet, want to delete it, or move or copy it, there’s one thing that you need to know if that sheet exists or not.

To write code to check whether the sheet exists or not you need a loop that loops through each sheet in the workbook and matches the name you have provided. But here’s the thing, you can use two different loops for this (For Next and For Each), and today we will use both.

In this tutorial, we will look at different ways to do that, so, make sure to have the developer tab on your ribbon and open the VBA editor to write this code.

Check IF a Sheet Exists in the Current Workbook

With this loop, you can refer to all the sheets in the workbook and loop through each one by one to match the name of the sheet with the sheet name that you want to search for.

Follow these steps:

  1. First, declare a variable to use for the sheet while performing the loop and to store the sheet name that you want to search.
    1-declare-a-variable-to-use-for-the-sheet
  2. Next, write a line of code for an input box to enter the name of the sheet that you wish to search.
    2-line-of-code-for-an-input-box
  3. After that, start your loop with the For Each keyword. And use the variable to refer to each worksheet in the workbook.
    3-start-your-loop
  4. From here, you need to write an IF THEN ELSE statement to match the name of the sheet with the name that you have entered in the input box, and then show a message box if match found and exit the procedure.
    4-write-an-if-then-else
  5. In the end, a message box to inform you if there’s no match found.
    5-message-box-to-show

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

Full Code:

Sub vba_check_sheet()

Dim sht As Worksheet
Dim shtName As String

shtName = InputBox(Prompt:="Enter the sheet name", _
Title:="Search Sheet")

For Each sht In ThisWorkbook.Worksheets

    If sht.Name = shtName Then

            MsgBox "Yes! " & shtName & " is there in the workbook."
            Exit Sub

    End If

Next sht

MsgBox "No! " & shtName & "is not there in the workbook."

End Sub

Let me explain how this works: When you run this code, it shows you a message where you need to enter the sheet name that you wish to find.

After that, it loops through each sheet to match the name with the name you have entered, and if the name matches with a sheet, it shows you a message and another message if there’s no match.

Here is another code to check if a sheet exists or not.

Sub vba_check_sheet()

Dim sht As Worksheet
Dim shtName As String
Dim i As Long

i = Sheets.Count

shtName = InputBox(Prompt:="Enter the sheet name", _
Title:="Search Sheet")

For i = 1 To i

    If Sheets(i).Name = shtName Then

            MsgBox "Yes! " & shtName & " is there in the workbook."
            Exit Sub

    End If

Next i

MsgBox "No! " & shtName & " is not there in the workbook."

End Sub

This code uses the FOR NEXT loop and uses the total count of sheets in the workbook, and based on that, perform a loop in each sheet that matches the name with the name you have entered.

Check IF Sheet Exists in Closed Workbook

In the following code, you have a loop that searches for the sheet name in a closed workbook. To refer to the file, we used the file address.

Sub vba_check_sheet()

Dim wb As Workbook
Dim sht As Worksheet
Dim shtName As String

shtName = InputBox(Prompt:="Enter the sheet name", _
Title:="Search Sheet")

Application.ScreenUpdating = False

Set wb = Workbooks.Open _
("C:UsersDellDesktopsample-file.xlsx")

For Each sht In wb.Worksheets

    If sht.Name = shtName Then

        wb.Close SaveChanges:=True
        MsgBox "Yes! " & shtName & " is there in the workbook." _
        , vbInformation, "Found"
        Exit Sub

    End If

Next sht

Application.ScreenUpdating = False

MsgBox "No! " & shtName _
& " is not there in the workbook.", _
vbCritical, "Not Found"

End Sub

When you run this macro, it opens the file at the back end as you have turned OFF the screen updating, and once it loops through all the sheets, you have code to turn ON the screen updating.

Note: As you can see, in the file location address, we have the file extension that means you need to have the correct extension of the file to refer to it.

More Tutorials on VBA Worksheets

  • Back to VBA Worksheet / VBA Tutorial

In this post you will learn how to check whether a particular worksheet exists inside a workbook. There are few different ways to check it. I will show you two methods here. In both methods we are going to use the name of the worksheet to identify the existence. First method will use a string comparison function and the second method will use an error handling technique.

Table of contents
Check if sheet exists — Method 1
Check if sheet exists — Method 2
Check if sheet exists and then delete using VBA
If sheet does not exist then skip

Here is a sample workbook which contains a few worksheets.

Sample workbook with 3 sheets

This workbook has three worksheets. Names of the worksheets are “Input”, “Tmp” and “Output”. Assume we want to check if sheet “Tmp” exists inside this workbook. Here is the first function you can use to check that.

Function IsSheetExist(WB As Workbook, SheetName As String) As Boolean

     Dim WS As Worksheet

     For Each WS In WB.Worksheets
          If StrComp(SheetName, WS.Name, vbTextCompare) = 0 Then
               IsSheetExist = True
               Exit Function
          End If
     Next WS

End Function

And this is how you can call this function from a subroutine.

Sub Test_1()

     Dim WB_Data As Workbook
     Dim Result As Boolean

     Set WB_Data = ActiveWorkbook

     Result = IsSheetExist(WB_Data, «Tmp»)

     MsgBox Result

End Sub

If you run the macro when the “Tmp” sheet is available inside the workbook then you will see this message box.

Result of first function when sheet is available

This is the result you will see when there is no “Tmp” sheet.

Result of first function when sheet is not in the workbook

Below is the explanation for the first function.

This function has two parameters. And the data type of the return value is boolean.

Function IsSheetExist(WB As Workbook, SheetName As String) As Boolean

Function uses a For Each Next statement to iterate through the sheets of the given workbook.

For Each WS In WB.Worksheets

Next WS

StrComp function is used to compare the given name with each and every sheet name.

If StrComp(SheetName, WS.Name, vbTextCompare) = 0 Then

End If

Learn more about StrComp function

If a match is found then the function will return the value “True” and exit.

For Each WS In WB.Worksheets
     If StrComp(SheetName, WS.Name, vbTextCompare) = 0 Then
          IsSheetExist = True
          Exit Function
     End If
Next WS

If the function is unable to find a matching sheet name inside the For Each Next statement, the code will be executed until the “End Function” line. Then the function will return false as the default value of a VBA function is false.

In this method we are going to use error handling techniques to check if a sheet exists in a workbook. Below is the complete code for the second function.

Function IsSheetExist(WB As Workbook, SheetName As String) As Boolean

     Dim WS As Worksheet

     On Error Resume Next
     Set WS = WB.Worksheets(SheetName)

     If Err <> 0 Then
          IsSheetExist = False
     Else
          IsSheetExist = True
     End If

     On Error GoTo 0

End Function

You can call this function from a subroutine same as we did above for the first function.

Set WS = WB.Worksheets(SheetName)

If there is no sheet named as SheetName then the above line will generate an error like this.

Run time error

To prevent that run-time error “On Error Resume Next” statement is used before that line. So the program will execute the next lines without raising the error. Next the below part will identify whether there is an error or not and output return value for the function accordingly.

If Err <> 0 Then
     IsSheetExist = False
Else
     IsSheetExist = True
End If

In VBA we use <> for not equal. It is the opposite of = symbol. So Err<>0 means error is not equal to zero. So there is an error. Then we can decide that the error occurred due to there not being such a sheet. So we return false for the function. Else we can return true.

So we learnt two different ways to check if a sheet exists inside a workbook. Sometimes we have to take some other actions after checking the existence of a particular sheet. Now let’s look at a few examples where we need to take another action after checking the existence of a sheet.

Check if sheet exists and delete using VBA

Sometimes you may need to check whether a particular sheet exists and then delete it if it exists. Here is one way to do it.

Function DeleteIfSheetExist(WB As Workbook, SheetName As String) As Boolean

     Dim WS As Worksheet

     For Each WS In WB.Worksheets
          If StrComp(SheetName, WS.Name, vbTextCompare) = 0 Then
               Application.DisplayAlerts = False
               WS.Delete
               Application.DisplayAlerts = True
               Exit Function
          End If
     Next WS

End Function

You can call the above function inside a subroutine like this.

Sub Test_3()

     Dim WB_Data As Workbook

     Set WB_Data = ActiveWorkbook

     Call DeleteIfSheetExist(WB_Data, «Tmp»)

End Sub

You might wonder why you need to check the existence of the sheet. You can delete the sheet straight away. Then if an error raises when there is no sheet with that name you can use “On Error Resume Next” to proceed without any interruption. Actually you can delete the sheet without checking its existence. But the problem is that errors can be raised due to different other reasons. For example, an error can be raised if you try to delete a sheet of a protected workbook. However there is a turnaround for that as well. You can identify the reason for the runtime error using the err number and then develop the code accordingly.

If sheet does not exist skip

Sometimes you may need to skip some processes if a sheet does not exist. For an example assume you want to call another subroutine if a sheet exists and skip if it doesn’t.

Sub CallAnotherSubIfSheetExist()

     Dim WB As Workbook
     Dim WS As Worksheet
     Dim SheetName As String

     Set WB = ActiveWorkbook
     SheetName = «Tmp»

     On Error Resume Next
     Set WS = WB.Worksheets(SheetName)

     If Err <> 0 Then
          ‘Do nothing
     Else
          On Error GoTo 0
          Call OtherSub
     End If

     On Error GoTo 0

End Sub

Also you can shorten the above if statement section like this as well.

Sub CallAnotherSubIfSheetExist()

     Dim WB As Workbook
     Dim WS As Worksheet
     Dim SheetName As String

     Set WB = ActiveWorkbook
     SheetName = «Tmp»

     On Error Resume Next
     Set WS = WB.Worksheets(SheetName)

     If Err = 0 Then
          On Error GoTo 0
          Call OtherSub
     End If

     On Error GoTo 0

End Sub

There may come a time when you need to know if a sheet in a workbook exists either during VBA code execution or as a result within the workbook. You may be creating and deleting sheets with your VBA code and will need to test if a sheet exists before it’s created/deleted to avoid run-time errors. You may also have functions in your workbook that depend on sheets you’re creating or deleting and you need to check if they exist.

A User Defined Function To Check If A Sheet Exists Within The Current Workbook

This is a simple VBA function that will return true if the current workbook contains a sheet with the exact name passed through the function and returns false otherwise. This function is not case sensitive so Sheet1 and SHEET1 are considered to be the same (sheet names in Excel are not case sensitive). Here the VBA is formatted as a user defined function.

Function WorksheetExists(SheetName As String) As Boolean
    
Dim TempSheetName As String

TempSheetName = UCase(SheetName)

WorksheetExists = False
    
For Each Sheet In Worksheets
    If TempSheetName = UCase(Sheet.Name) Then
        WorksheetExists = True
        Exit Function
    End If
Next Sheet

End Function

With this code we can use =WorksheetExists(B3) to test any text string to see if it exists as a sheet name in the current workbook.

About the Author

John MacDougall

John is a Microsoft MVP and qualified actuary with over 15 years of experience. He has worked in a variety of industries, including insurance, ad tech, and most recently Power Platform consulting. He is a keen problem solver and has a passion for using technology to make businesses more efficient.

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

Проверка существования листа в рабочей книге Excel из кода VBA с помощью присвоения его объектной переменной или перебора существующих листов циклом.

Присвоение листа объектной переменной

Пользовательская функция VBA Excel для проверки существования листа в рабочей книге путем определения результата присвоения ссылки на него объектной переменной. Присвоение состоялось (SheetExist = True) – искомый лист существует, произошла ошибка и присвоение не состоялось (SheetExist = False) – лист не существует.

Function SheetExist(WbName As String, ShName As String) As Boolean

Dim mySheet As Worksheet

    On Error Resume Next

        Set mySheet = Workbooks(WbName).Sheets(ShName)

    SheetExist = Not mySheet Is Nothing

End Function

Аргументы функции SheetExist:

  • WbName – имя открытой рабочей книги, в которой ищется лист.
  • ShName – имя искомого рабочего листа.

Перебор существующих листов циклом

Проверка существования рабочего листа в книге Excel с помощью перебора существующих листов циклом VBA и сравнения их имен с именем искомого листа. Совпадение найдено (SheetExist = True) – искомый лист существует, совпадение не найдено (SheetExist = False) – лист не существует.

Function SheetExist(WbName As String, ShName As String) As Boolean

Dim mySheet As Worksheet

    For Each mySheet In Workbooks(WbName).Sheets

        If mySheet.Name = ShName Then

            SheetExist = True

            Exit Function

        End If

    Next

End Function

Пример проверки существования листа

Пример проверки существования искомого листа в рабочей книге Excel с помощью пользовательской функции VBA SheetExist:

Sub Primer()

    If SheetExist(ThisWorkbook.Name, «Лист1») Then

        MsgBox «Лист существует»

    Else

        MsgBox «Лист не существует»

    End If

End Sub

Имя сторонней открытой книги должно быть указано вместе с расширением:

...

    If SheetExist(«Книга2.xlsm», «Лист2») Then

...

Обратите внимание, если книга, имя которой указано в параметре WbName закрыта или не существует, будет сгенерирована ошибка.

Чтобы функция проверки существования рабочего листа SheetExist была доступна из модуля любой книги Excel на вашем компьютере, разместите ее в Личной книге макросов.


Return to VBA Code Examples

In this Article

  • Check if Sheet Exists
    • Check if Sheet Exists
    • Check if Range Exists on a Sheet
    • Adjusting the RangeExists Function

Check if Sheet Exists

We’ve created a function that will test if a Sheet or Range (on a particular sheet) exists. The Range test is useful if you want to check if a particular named range exists on a sheet.

'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

Place the function within a VBA Code Module and you can access it by using sub procedures like these:

Check if Sheet Exists

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

Check if Range Exists on a Sheet

Sub Test_RangeExists()
    MsgBox RangeExists("setup", "rngInput")
End Sub

Adjusting the RangeExists Function

Check if Sheet Exists on Another Workbook

The above function looked at ActiveWorkbook (the currently active workbook). Instead you could adjust the Function to look at a specific workbook like this:

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

Implementation:

Sub Test_WBSheet_Exists()
    Dim wb As Workbook
    Set wb = ActiveWorkbook

    MsgBox RangeExists(wb, "Sheet1")

End Sub

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!
vba save as

Learn More!

I have the following code that’s not working as expected:

If Sheets("a") <> "" Then MsgBox ("sheet a exists")

How can I tell if sheet a exists in the workbook?

DavidPostill's user avatar

DavidPostill

150k77 gold badges348 silver badges386 bronze badges

asked Feb 16, 2016 at 16:34

DanM's user avatar

I’d make a separate function for it:

Function SheetExists(SheetName As String)
    On Error GoTo no:
    WorksheetName = Worksheets(SheetName).Name
    SheetExists = True
    Exit Function
no:
    SheetExists = False
End Function

Then you can easily call it where needed, even in a formula if you wanted:

Sub ABC()
    If SheetExists("Test") Then
        MsgBox "Yay!"
    Else
        MsgBox "Boo!"
    End If
End Sub

or

=If(SheetExists("Test"),"Yay!","Boo")

answered Feb 16, 2016 at 18:00

Jonno's user avatar

JonnoJonno

20.9k4 gold badges61 silver badges70 bronze badges

2

Something like:

Sub DoesSheetExist()
    Dim s As Worksheet

    For Each s In Sheets
        If s.Name = "a" Then
            MsgBox "Sheet a exists"
            Exit Sub
        End If
    Next s
    MsgBox "Sheet a does not exist"
End Sub

answered Feb 16, 2016 at 17:13

Gary's Student's user avatar

Gary’s StudentGary’s Student

19.2k6 gold badges25 silver badges38 bronze badges

2

You can check for the error. eg:

Dim A As String
    On Error Resume Next
        A = Worksheets("a").Name
        Select Case Err.Number
            Case 9
                MsgBox "Sheet ""a"" does not exist"
            Case 0
                MsgBox "Sheet ""a"" exists"
            Case Else
                Stop
        End Select
    On Error GoTo 0

answered Feb 16, 2016 at 17:50

Ron Rosenfeld's user avatar

Ron RosenfeldRon Rosenfeld

7,9113 gold badges13 silver badges16 bronze badges

In the template that I made for AutoFilter, I used a function and procedure to check whether a worksheet is available. In the codes below, it is checked whether the DATA sheet is in the workbook :

Sub Sht_Cntrl()
    If Not Sheet_Exists_Cntrl("DATA") Then
    ThisWorkbook.Sheets.Add( _
    After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)).Name = "DATA"
    End If
 End Sub

Function Sheet_Exists_Cntrl(SheetName As String) As Boolean
    Dim sht As Excel.Worksheet
    On Error GoTo eHandle
    Set sht = ThisWorkbook.Worksheets(SheetName)
    Sheet_Exists_Cntrl = True
    Exit Function
eHandle:
    Sheet_Exists_Cntrl = False
End Function

When the Sht_Cntrl procedure is called (Call Sht_Cntrl) it is created if DATA sheet does not exist.

enter image description here

You can view the codes by downloading the sample template from this page : Vba autofilter with listbox

answered Jan 27, 2021 at 20:51

kadrleyn's user avatar

If (Worksheets("a").Name <> "") Then MsgBox ("sheet A exists")

this works as expected

answered Feb 16, 2016 at 16:43

DanM's user avatar

DanMDanM

4903 gold badges9 silver badges22 bronze badges

1

  1. Check if Sheet Exists in VBA
  2. Check if Sheet Exists in Closed Workbook in VBA

Check if Sheet Exists in VBA

We will introduce how to check if a sheet exists using VBA in Excel.

Check if Sheet Exists in VBA

While working on multiple sheets, there may be some duplicate sheets, or we may want to save ourselves from creating any duplicate sheets. For this purpose, we can use VBA to check if there are any sheets with the same name for which we may want to create a sheet.

To check whether the sheet exists, we require a loop along with each sheet in the workbook and compare the names we have created. We will use two loops; one will be the For each loop, and the second one will be the If Else statement.

First, we will create two variables: one will store the worksheet, and the second one will store the sheet’s name for which we want to look for duplicates or check if the sheet with this name exists. We will use the for loop to go through all the files in a folder and the if-else statement to check if the sheet’s name exists with the same name as the other sheet.

If the file exists with the same name, we will show a message box that says that the sheet exists. Otherwise, the message box will display that the sheet doesn’t exist.

Code:

#VBA
Sub sheetCheck()

Dim sheet As Worksheet
Dim Name As String

Name = "Sheet1"

For Each sheet In ThisWorkbook.Worksheets

    If sheet.Name = Name Then

            MsgBox "Yes! " & Name & " is there in the workbook."
            Exit Sub

    End If

Next sheet

MsgBox "No! " & Name & "is not there in the workbook."

End Sub

Output:

checking sheet exists or not

When we searched for sheet1, we got the positive response that the sheet with the same name already exists.

Check if Sheet Exists in Closed Workbook in VBA

There may be some situations where we may also want to check for the sheets in an excel file that are closed or on which we have already worked. We can also check for the sheets in closed excel files by opening the files using the VBA and the For each loop with the If else statement as we used in the above example.

Let’s try to check for the sheet in a closed excel file.

Code:

#VBA
Sub checkSheet()

Dim book As Workbook
Dim sheet As Worksheet
Dim Name As String

Name = "Sheet1"

Application.ScreenUpdating = False

Set book = Workbooks.Open _
("C:UsersHp9470DocumentsBook2.xlsx")

For Each sheet In book.Worksheets

    If sheet.Name = Name Then

        book.Close SaveChanges:=True
        MsgBox "Yes! Sheet Exists"
        Exit Sub

    End If

Next sheet

Application.ScreenUpdating = False

MsgBox "No! Sheet doesn't exists"

End Sub

Output:

checking sheet exists or not in closed excel sheet

The sheet exists in the closed excel file we accessed using the open function. In this way, we can check both opened and closed files about sheets using the name way.

Like this post? Please share to your friends:
  • Vba excel cells формат
  • Vba excel cells строка столбец
  • Vba excel cells или range
  • Vba excel cells диапазон ячеек
  • Vba excel cells text