Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether certain sheets exist or not in Excel-VBA? [duplicate]

Does anyone know how to check whether certain sheets exist or not in an Excel document using Excel VBA?

like image 461
Vivian Avatar asked Jul 27 '11 01:07

Vivian


2 Answers

Although (unfortunately) such method is not available, we can create our own function to check this..

Hope the code below fits your needs.

Edit1: Added also delete statement...

Sub test()

    If CheckSheet(Sheets(3).Name) then

        Application.DisplayAlerts = False
        Sheets(Sheets(3).Name).Delete
        Application.DisplayAlerts = True

    End If

End Sub

The solution I'd go for...

Function CheckSheet(ByVal sSheetName As String) As Boolean

    Dim oSheet As Excel.Worksheet
    Dim bReturn As Boolean

    For Each oSheet In ActiveWorkbook.Sheets

        If oSheet.Name = sSheetName Then

            bReturn = True
            Exit For

        End If

    Next oSheet

    CheckSheet = bReturn

End Function

Alternatively, if you don't mind to use code that actively raise errors (which is not recommended by common coding best practices) you could use this 'Spartan Programming wannabe' code below...

Function CheckSheet(ByVal sSheetName As String) As Boolean

    Dim oSheet As Excel.Worksheet
    Dim bReturn As Boolean

    For Each oSheet In ActiveWorkbook.Sheets

        If oSheet.Name = sSheetName Then

            bReturn = True
            Exit For

        End If

    Next oSheet

    CheckSheet = bReturn

End Function


Function CheckSheet(ByVal sSheetName As String) As Boolean

    On Error Resume Next
    Dim oSheet As Excel.Worksheet

    Set oSheet = ActiveWorkbook.Sheets(sSheetName)
    CheckSheet = IIf(oSheet Is Nothing, False, True)

End Function
like image 69
Tiago Cardoso Avatar answered Oct 24 '22 06:10

Tiago Cardoso


Something like this will get you started:

On Error Resume Next

Dim wSheet as Worksheet
Set wSheet = Sheets(1) ' can also be a string, such as Sheets("Sheet1")

If wSheet Is Nothing Then
    MsgBox "Worksheet not found!"
    Set wSheet = Nothing ' make the worksheet point to nothing. 
    On Error GoTo 0 
Else 
    MsgBox "Worksheet found!"
    Set wSheet = Nothing ' set the found Worksheet object to nothing.  You can use the found wSheet for your purposes, though.  
End If

This code was based on http://www.ozgrid.com/VBA/IsWorkbookOpen.htm. Look for the DoesSheetExist() sub.

Hope this helps!

like image 37
Paul McLain Avatar answered Oct 24 '22 07:10

Paul McLain