Dim wkbkdestination As Workbook
Dim destsheet As Worksheet
For Each ThisWorkSheet In wkbkorigin.Worksheets
\'this throws subscript out of range if there is not
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
Short and clean:
Function IsSheet(n$) As Boolean
IsSheet = Not IsError(Evaluate(n & "!a1"))
End Function
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
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") ...
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
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.