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 know it is an old post, but here is another simple solution that is fast.
Public Function worksheetExists(ByVal wb As Workbook, ByVal sheetNameStr As String) As Boolean
On Error Resume Next
worksheetExists = (wb.Worksheets(sheetNameStr).Name <> "")
Err.Clear: On Error GoTo 0
End Function
Some folk dislike this approach because of an "inappropriate" use of error handling, but I think it's considered acceptable in VBA... An alternative approach is to loop though all the sheets until you find a match.
Function WorksheetExists(shtName As String, Optional wb As Workbook) As Boolean
Dim sht As Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set sht = wb.Sheets(shtName)
On Error GoTo 0
WorksheetExists = Not sht Is Nothing
End Function
wsExists
function (without reliance on Error Handling!)Here's a short & simple function that doesn't rely on error handling to determine whether a worksheet exists (and is properly declared to work in any situation!)
Function wsExists(wsName As String) As Boolean
Dim ws: For Each ws In Sheets
wsExists = (wsName = ws.Name): If wsExists Then Exit Function
Next ws
End Function
The following example adds a new worksheet named myNewSheet
, if it doesn't already exist:
If Not wsExists("myNewSheet") Then Sheets.Add.Name = "myNewSheet"
Why not just use a small loop to determine whether the named worksheet exists? Say if you were looking for a Worksheet named "Sheet1" in the currently opened workbook.
Dim wb as Workbook
Dim ws as Worksheet
Set wb = ActiveWorkbook
For Each ws in wb.Worksheets
if ws.Name = "Sheet1" then
'Do something here
End if
Next