Jain
Jain

Reputation: 999

Using Error Handling in VBA

I am trying to figure out if it is possible for all my subs to have a single error handler? I am in a condition where I need to exit the sub whenever there is an error and skip all of the next subs.

Sub Runall()
Call A
Call B
Call C 
Call D
End sub 

Now if there is a error in Sub A I don't want to run B,C,D and same thing for B. Where Should my I put my error handler? I am practically very confused as how does use of EXIT statement matter. Please advice.

Upvotes: 0

Views: 127

Answers (2)

sgp667
sgp667

Reputation: 1875

Here is how I would do it.
Include on On Error GoTo Handler: in calling sub.

Once these subs raise an error On Error in RunAll will take over(becuase if a sub is missing Error handler it will try to use Error Handler of calling sub) and with its GoTo is will skip everything untill it sees Handler.

Remeber that before Handler you need to incluse Exit Sub or VBA in Handler will be used regardless of if you have an error or not.

Here is a "failling" example:

Sub RunAll()
    On Error GoTo Handler
    Call A
    Call B
    Exit Sub
Handler:
        Debug.Print "testing"
End Sub

A

Sub A()
    Dim fail As Integer

    fail = 1 / 1
End Sub

B

Sub B()
    Dim fail As Integer

    fail = 1 / 0
End Sub

Upvotes: 1

Dmitrij Holkin
Dmitrij Holkin

Reputation: 2055

Try this

 Sub Runall()
    Call A
    On Error GoTo Errhandler
    Call B
    On Error GoTo Errhandler
    Call C 
    On Error GoTo Errhandler
    Call D
    On Error GoTo Errhandler

 ' Exit the macro so that the error handler is not executed.
 Exit Sub
    Errhandler:
    ' If an error occurs, display a message and end the macro.
    MsgBox "An error has occurred. The macro will end."
 End sub 

Upvotes: 1

Related Questions