views:

253

answers:

5

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
+7  A: 

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.

CAbbott
+1  A: 

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)

Alan Moore
A: 

need to add exit else the program continues to execute the label as it is the part of the code

A: 

Just as a clarification to add some meat to the other answers.

"err_handle:" is only error handling code because you are using it as such. It isn't intrinsically an error handler like a catch block in other languages.

Technically "err_handle:" is just a label that facilitates a goto jump. In your case the goto just happens to be used with an error handler (on error goto)

JohnFx
A: 

The generally accepted pattern for error handling is to have an error handler and an exit procedure. A pretty standard code stump might look like this:

Public Function Example() As String
    Dim strRtnVal As String 'Return value variable.
    On Error GoTo Err_Hnd
    '***************************************************************************
    'Lock interface code here (hourglass, screenupdating etc.)
    '***************************************************************************

    '***************************************************************************
    'Your code here.
    '***************************************************************************
Exit_Proc:
    'Prevents "Error Loops" caused by errors within the exit procedure:
    On Error Resume Next
    '***************************************************************************
    'Restore Interface.
    '***************************************************************************
    Example = strRtnVal 'Set Return Value.
    Exit Function
Err_Hnd:
    'Display message, do some logging, whatever.
    Resume Exit_Proc '<- Run exit procedure.
End Function
Oorang