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

Err Object

This does not automatically clear the Err object.
When you are checking the Err object to handle the error you should always clear the Err object.


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