Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why VBA goes to error handling code when there is no error?

I have writen some code in VBA (Excel) with error handling labels. It worked fine until I recently notice the error handling code gets executed everytime, not just when an error occurs. Does anybody know why this happens? Thanks.

Here's a trivial test case where both msgboxes would pop up.

Sub example()
    On Error GoTo err_handle
    MsgBox "OK!"
err_handle:
MsgBox "not OK"
End Sub
like image 538
Martin08 Avatar asked Dec 05 '22 05:12

Martin08


2 Answers

You want to add an Exit Sub to your routine:

Sub example()
    On Error GoTo err_handle
    MsgBox "OK!"
    Exit Sub
    err_handle:
    MsgBox "not OK"
End Sub

Look here for a full explaination.

like image 196
CAbbott Avatar answered Feb 24 '23 09:02

CAbbott


It's because you aren't returning out of the subroutine after the first message box the (OK) one. After that is shown the next line of code is executed which is the "not ok" message.

You could either exit the subroutine early before your error handler label (ExitSub) or goto the end of the subroutine on success (bypassing the "error" routine)

like image 42
Alan Moore Avatar answered Feb 24 '23 10:02

Alan Moore