On Error GoTo -1

This statement resets the Err Object AND resets/clears the VBA Error memory.

Public Sub MySubroutine() 
   On Error GoTo -1

In most situations On Error GoTo -1 does exactly the same as Err.Clear although there is a subtle difference.


Using Line Labels

This statement can be used to allow multiple errors to be handled using line labels in the same subroutine.
This is not recommended because having multiple line labels is confusing to debug.

Public Sub MultipleRuntimeErrors() 
Dim iInteger As Integer
   On Error GoTo ErrorHandler1
   iInteger = 40000
   Exit Sub

ErrorHandler1:
   Debug.Print "Overflow"

   On Error GoTo -1
'Err.Clear 'does not reset/clear the VBA memory

   On Error GoTo ErrorHandler2
   Debug.Print 1 / 0
   Exit Sub

ErrorHandler2:
   Debug.Print "Division by Zero"
End Sub

If you replace "On Error GoTo -1" with "Err.Clear" you will see different results.
Using Err.Clear will display the error message but On Error GoTo -1 will reset everything so the second error handler will work.


Using Resume Next

The Err.Clear method can be used to allow multiple errors to be handled using Resume Next in the same subroutine.
This is not recommended because there is a risk of catching the previously handled error.

Public Sub MultipleRuntimeErrors_Resume() 
Dim iInteger As Integer
   On Error Resume Next
   iInteger = 40000

   If (Err.Number <> 0) Then
      Debug.Print "Overflow"
      Err.Clear
   End If

   Debug.Print 1 / 0

   If (Err.Number <> 0) Then
      Debug.Print "Division by Zero"
      Err.Clear
   End If
End Sub

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