How to manage the no error case when handling erro

2019-04-28 06:18发布

I need to catch some VBA error using the GoTo statement like this :

Sub mySub
 On Error GoTo errorHandler:
    Workbooks.Open("myWorkbook")
'
' Some Code
'
errorHandler:
MsgBox "ERROR"

End Sub

The problem is that when there is no error the errorHandler section is executed.
I found this discussion but the answer doesn't solve my issue.
I tried adding an Exit Sub statement as explained :

Sub mySub
 On Error GoTo errorHandler:
    Workbooks.Open("myWorkbook")
    Exit Sub

'
' Some Code
'
errorHandler:
  MsgBox "ERROR"

End Sub

In this case it exits the method when there is no error. I also tried :

 Sub mySub
 On Error GoTo errorHandler:
    Workbooks.Open("myWorkbook")
'
' Some Code
'
errorHandler:
  MsgBox "ERROR"
  Exit Sub
End Sub

But still the same issue: The errorHandler is executed even when no errors occur.

7条回答
冷血范
2楼-- · 2019-04-28 06:56

This is what I have done. Works like a charm

Sub someProgram ()
    On Error goto Handler:
        x = 7/0

    'Some code you wanna execute  with or without error
Exit Sub

Handler:
     'Write your handler here

Resume next 'After handling error, this line will help you resume the next line

End sub
查看更多
登录 后发表回答