If Error(Sheets(ws_str)) = True Then Exit Sub
Returns run-time error 9. I know this sheet does not exist. How do I do errorhandling in cases where the worksheet does not exist?
If Error(Sheets(ws_str)) = True Then Exit Sub
Returns run-time error 9. I know this sheet does not exist. How do I do errorhandling in cases where the worksheet does not exist?
Try the little piece of code below:
Option Explicit
Sub SheetExits()
Dim ws As Worksheet
Dim ws_str As String
ws_str = "aaa" ' for test
On Error Resume Next
Set ws = Worksheets(ws_str)
On Error GoTo 0
If ws Is Nothing Then Exit Sub
End Sub
This will solve your problem:
Sub ErrorHandling()
On Error GoTo ExitSub
Dim ws As Worksheet
Set ws = Worksheets("NonExistingSheet") 'it will throw an error
MsgBox ("This won't be displayed")
ExitSub:
End Sub
Basically, at the beginning define, where your code should resume in case of an error. To satisfy your requirement, place the resuming point right before End Sub, so it goes directly there in case of an error.
Function SheetExists(sheetname as string) as boolean
On error goto whoops
dim ws as worksheet
set ws = worksheets(sheetname)
set ws = nothing
sheetexists = true
exit function
whoops:
sheetexists = false
end function