On Error Resume Next

This statement allows execution to continue, effectively ignoring all run-time errors. This is not recommended.

Public Sub MySubroutine() 
    On Error Resume Next

The "Next" does not refer to the next line after this statement.
The "Next" refers to continuing the execution on the subsequent line, after the error has occurred.
This causes execution to continue with the statement immediately following the statement that caused the run-time error.
Be careful when using this statement because this will ignore run-time errors that could be unexpected.
Ignoring run-time errors will lead to logical-errors and unexpected behaviour.

Public Sub RuntimeErrorIsIgnored() 
    On Error Resume Next
'do something
    Charts("Chart 1").Activate 'this generates a run-time error
'execution continues
End Sub

This statement allows execution to continue when multiple run-time errors occur.

Public Sub MultipleRuntimeErrorsAreIgnored() 
    On Error Resume Next
    Charts("Chart 1").Activate 'this generates a run-time error
'execution continues
    Charts("Chart 2").Activate 'this generates another run-time error
'execution continues
End Sub

If you are anticipating a run-time error you can handle this by checking the Err Object.
When a run-time error occurs the Err object will contain details about the error.
You should always reset the Err object after the error has been handled.

Public Sub RuntimeErrorIsHandled() 
    On Error Resume Next
    Charts("Chart 1").Activate 'this generates a run-time error
    If Err.Number <> 0 Then
        Call MsgBox("Error")
        Err.Clear 'reset the Err object
    End If
End Sub

Nested Subroutines

Unhandled run-time errors are passed up the call stack.
This "On Error Resume Next" error handling statement is still active inside the MySub2 subroutine.

Public Sub MySubroutine() 
   On Error Resume Next
   Call MySub2 'the run-time error is ignored
End Sub

Public Sub MySub2()
   Charts("Chart 1").Activate 'this generates a runtime error
End Sub

Switching Off

You can turn this type of error handling off by using the "On Error GoTo 0" to switch back to the default type of error handling.

   On Error GoTo 0 
'continue with normal error handling
End Sub

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext