VBA Nested On Error GoTo
You can't use an On Error statement within an error handler. See e.g. this article that explains this.
What you CAN do however is to have a separate routine that handles the "regular error". This routine can have a "fatal error" handler. Your code would then look something like this:
(Edit: Edited the code to enable exit when there is a fatal error):
Sub DoThings()
On Error GoTo SmallError
Dim fatalExit As Boolean
'Coding Happens
Do While(conditionhere)
'Looping things happen
LoopResume:
count = count + 1
Loop
On Error Goto SmallError2
'Finishing code happens
Exit Sub
SmallError:
handleError Err.Source, Err.Description, fatalExit
If fatalExit Then
Exit Sub
Else
Resume LoopResume
End If
SmallError2:
handleError Err.Source, Err.Description, fatalExit
Exit Sub
End Sub
Private Sub handleError(ByVal source As String,ByVal description As String, ByRef fatalExit As Boolean)
On Error Goto FatalError
'Do "small error" handling here
Exit Sub
FatalError:
fatalExit = True
'Do "fatal error" handling here
End Sub
steventnorris
Applications developer with a preference for object-oriented languages. Currently working at FortyAU, a development firm in Nashville, TN. http://www.fortyau.com
Updated on June 04, 2022Comments
-
steventnorris almost 2 years
I have VBA code that is supposed to be nested error checking, but it does not. The code is psuedo as below. However, whenever an error occurs within an error (For instance, an error is tripped in the loop, goto SmallError occurs, and an error occurs in SmallError) The second GoTo is not used. The error then breaks the code.
Ex:
Error in Loop
GoTo SmallError
Error in SmallError
Code Breaks (Here code should GoTo FatalError)
Sub DoThings() On Error GoTo SmallError 'Coding Happens Do While(conditionhere) 'Looping things happen GoTo LoopResume SmallError: source = Err.source descript = Err.Description On Error GoTo Fatal Error 'Small error processing happens Resume LoopResume FatalError: source = Err.source descript = Err. Description On Error GoTo ExitError 'Fatal Error processing happens ExitError: Exit Sub LoopResume: count = count + 1 Loop On Error GoTo FatalError 'Finishing code happens End Sub