Does anyone know how to check whether certain sheets exist or not in an Excel document using Excel VBA?
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