Link to home
Start Free TrialLog in
Avatar of RWayneH
RWayneHFlag for United States of America

asked on

Does Sheet tab exist?

I am looking for some VBA that looks for a specific sheet tab name, and if it exists fine, if not create it.  Has anyone done this before?
Avatar of Subodh Tiwari (Neeraj)
Subodh Tiwari (Neeraj)
Flag of India image

Try something like this.....
Sub CreateSheetIFDoesNotExist()
Dim ws As String
ws = "Sheet5"   'Checking if Sheet5 exists
If Not WorksheetExists(ws) Then
    Worksheets.Add(after:=Worksheets(Worksheets.Count)).Name = ws
End If
End Sub

Function WorksheetExists(shName As String) As Boolean
On Error Resume Next
WorksheetExists = CBool(Len(Worksheets(shName).Name) > 0)
End Function

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Saurabh Singh Teotia
Saurabh Singh Teotia
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can also iterate the worksheets, looking for a worksheet with a particular name.
Example:
Function WksExists(parmName As String) As Boolean
    Dim wks As Worksheet
    For Each wks In Worksheets
        If wks.Name = parmName Then
            WksExists = True
            Exit Function
        End If
    Next    
    WksExists = False
End Function

Open in new window


Although I wrote it this article about Access objects, the basic principles apply for Excel:
https://www.experts-exchange.com/articles/6670/Object-Existence.html
Avatar of RWayneH

ASKER

Yup worked fine.  Thanks.