Check for the existence of a worksheet

llanllwni

New Member
Joined
Feb 10, 2003
Messages
1
Is there anyway of using VBA to check if a workbook contains a specific worksheet? Eg. if 'ABC.xls' contains the worksheet 'Sheet2'

Appreciate any help or guidance.

Thank you.
 

Excel Facts

What is =ROMAN(40) in Excel?
The Roman numeral for 40 is XL. Bill "MrExcel" Jelen's 40th book was called MrExcel XL.
Try some code like this:

Code:
Sub CheckSheet()

    On Error GoTo Err_check
    Sheets("Sheet2").Select
    
    Exit Sub
    
Err_check:
    If Err.Number = 9 Then
        MsgBox "No such sheet exits"
        Resume Next
    Else
        MsgBox Err.Number & " " & Err.Description
    End If
    
End Sub

Obviously, replace "Sheet2" with whatever sheet name you are looking for.
This message was edited by jmiskey on 2003-02-11 08:35
 
Upvote 0
Hi,

You might like to include the test in a function. That way you can make use of it as and when you need to (it also helps to make your code easier to maintain). <pre>Sub test()
Dim shtName As String
shtName = "Sheet2"
MsgBox "Does " & shtName & " exist? : " & WorksheetExists(shtName)
End Sub

Function WorksheetExists(WorksheetName As String) As Boolean
Dim sht As Object
On Error Resume Next
Set sht = ActiveWorkbook.Sheets(WorksheetName)
WorksheetExists = (Err.Number = 0)
End Function</pre>HTH
 
Upvote 0
Here's a solution that will also tell you what visible value the sheet has ... if not found the function Returns "N/A"

Function SheetState(shName) As String
' will find all 3 states of sheets and report
On Error GoTo No
Select Case Sheets(shName).Visible
Case 0: SheetState = "Hidden"
Case -1: SheetState = "VeryHidden"
Case 2: SheetState = "Visible"
End Select
Exit Function
No: SheetState = "N/A"
End Function
 
Upvote 0

Forum statistics

Threads
1,214,397
Messages
6,119,273
Members
448,883
Latest member
fyfe54

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top