0

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.

1
  • Possible duplicate of this. Can you check the accepted answer and see if it works for you? Commented Apr 7, 2015 at 17:34

2 Answers 2

1

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Where can I put the error handler. Sorry but I create certain new sheets that I need to delete in case of any error Thanks.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.