Cyril
Cyril

Reputation: 6829

Cancelling a child subroutine via errorhandling from a parent subroutine

Background:

I'm attempting to plan out how to automate a task and am anticipating using multiple private subroutines, or functions, from another subroutine. I'll use parent-child language to try and keep things straight.

The parent subroutine is the one calling each of the children.

The child subroutines (children) will be called in order to perform their code.

I am trying to determine if I can have error handling in the parent to exit sub for a child and move to the next child.

Albeit the example code I will use is a very simple example of just adding 1 to i, the planned code would be more involved where resume next wouldn't be sufficient (not that ignoring an error is "good" practice).


Issue:

I am not having luck in searching if there is an existing on error to exit the current child and move to the next, where I have my on error line only in the parent.


Question:

Is there a way to exit sub the current child based on an error handling statement in the parent subroutine? Or, should I just stick to error handling in each child?


Code in Question:

Giving an gross example of what I am thinking; this is not working code.

Option Explicit
Public i As Long

Sub fdsa()
    on error ' exit called subroutine
    a
    s
    d
    f
    MsgBox i
End Sub

Private Sub a()
    i = i + 1
End Sub

Private Sub s()
    i = i + 1
End Sub

Private Sub d()
    i = i + 1 / 0
End Sub

Private Sub f()
    i = i + 1
End Sub

The messagebox would output "3" after the parent finishes.

Upvotes: 0

Views: 152

Answers (1)

Rory
Rory

Reputation: 34045

If the child routines have no error handler, then any errors will be passed back to the parent, at which point you can resume with the next one. All you need is on error resume next here:

Sub fdsa()
    on error resume next
    a
    s
    d
    f
    MsgBox i
End Sub

Upvotes: 1

Related Questions