How to manage the no error case when handling errors in VBA?
Just put Exit sub in.
Sub mySub
On Error GoTo myHandler:
Workbooks.Open("myWorkbook")
'
' Some Code
'
Exit sub
myHandler:
MsgBox "EROOR !"
err.clear
End Sub
Here's the pattern I prefer:
Sub SomeSub()
On Error GoTo ErrorLabel
'Code goes here
ExitLabel:
'Clean-up code, if any, goes here
Exit Sub
ErrorLabel:
'Error-handling code goes here
Resume ExitLabel
End Sub
Note that Resume
clears the error. I like this pattern for a few reasons:
- Habitually inserting the exit block before the error-handling block reduces the chance that I'll have the OP's problem of accidentally dropping into the error handler.
I use
GoTo ExitLabel
for any early exit from the Sub or Function. This way, I'm less likely to skip the clean-up code by accident. Example:Sub SomeOtherSub() Dim x As ResourceThatNeedsToBeClosed Dim i As Long On Error GoTo ErrorLabel Set x = GetX For i = 1 To 100 If x.SomeFunction(i) Then GoTo ExitLabel End If Next ExitLabel: x.Close ErrorLabel: 'Error-handling code goes here Resume ExitLabel End Sub