William Miranda
William Miranda

Reputation: 3

GoTo function is corrupt or has a limit

I want to put two GoTo aligned after detecting an error. However, the second GoTo is ignored by VBA, and then a debug screen appears.

Sub GoTo_Test()

Dim X, Y As Integer

1: On Error GoTo 2
                                            MsgBox "START 1"
    X = 1 / 0
                                            MsgBox "END 1"

2: On Error GoTo 3
                                            MsgBox "START 2"
    Y = 1 / 0
                                            MsgBox "END 2"

3:                                          MsgBox "End Sub"

End Sub

Upvotes: 0

Views: 186

Answers (3)

Storax
Storax

Reputation: 12167

Another way is to reset the error handler.

Sub GoTo_Test()

        Dim X, Y As Integer

1:        On Error GoTo 2
          MsgBox "START 1"
          X = 1 / 0
          MsgBox "END 1"

2:        On Error GoTo -1
          On Error GoTo 3
          MsgBox "START 2"
          Y = 1 / 0
          MsgBox "END 2"

3:        MsgBox "End Sub"

End Sub

Upvotes: 2

Ron Rosenfeld
Ron Rosenfeld

Reputation: 60199

Try:

Option Explicit

Sub GoTo_Test()

Dim X, Y As Integer

1: On Error GoTo 2
                                            MsgBox "START 1"
    X = 1 / 0
                                            MsgBox "END 1"

2: Resume Next
On Error GoTo 3
                                            MsgBox "START 2"
    Y = 1 / 0
                                            MsgBox "END 2"

3: Resume Next
                                            MsgBox "End Sub"

End Sub

You need to close (terminate) each active error handler else you'll have problems with errors within the active error handling routine.

Upvotes: 0

GSerg
GSerg

Reputation: 78155

Once you've entered an error handler subroutine, you need to exit that subroutine with Resume. Because you never did, the second exception is treated as an exception inside an error handler, which means the error handler failed to handle the error, so the error is propagated up.

If you insist on having the code laid out the way you sketched out, that would be

Sub GoTo_Test()
Dim X As Integer, Y As Integer

1: On Error GoTo 2
                                            MsgBox "START 1"
    X = 1 / 0
                                            MsgBox "END 1"

handled_2: On Error GoTo 3
                                            MsgBox "START 2"
    Y = 1 / 0
                                            MsgBox "END 2"

handled_3:                                  MsgBox "End Sub"

Exit Sub


2:
Resume handled_2

3:
Resume handled_3

End Sub

Upvotes: 4

Related Questions