You need Resume Next
to go to the next line after the line, causing the error. And Err.Clear
is a good practice as well.
The Exit Sub
before the errhandler
is also a good practice:
Sub SkipIteration()
Dim x As Long
For x = 5 To -5 Step -1
On Error GoTo errhandler:
Debug.Print 15 / x
Debug.Print "testing"
Next x
Exit Sub
errhandler:
If Err.Number = 11 Then
Debug.Print ("Error on " & x)
Err.Clear
Resume Next
End If
End Sub
The difference between Resume
and Resume Next
is the following:
Resume
tries to go back to where it was called.
In the TestMeResume
procedure, it throws Error 11 at the Debug.Print a/b and in the error handler it assigns b = 5. Then with Resume
it retries the Debug.Print a / b
, and as far as b
is not 0
, it runs.
Resume Next
goes to where it was called, ignores the line and continues with the next one.
In the TestMeResumeNext
procedure, error 91 is thrown at a = 12
and the error handler is triggered. In the error handler a is assigned to Range("A14")
and with Resume Next
the a = 12
is skipped and the Sub
continues.
Sub TestMeResumeNext()
On Error GoTo TestMeResumeNext_Error
Dim a As Range
a = 12 'Error 91 here!
Debug.Print a.Row 'Resume Next goes back here
Exit Sub
TestMeResumeNext_Error:
Set a = Range("A14")
Resume Next
End Sub
Sub TestMeResume()
On Error GoTo TestMeResume_Error
Dim a As Long: a = 10
Dim b As Long: b = 0
Debug.Print a / b 'Error 11 here the first time
Exit Sub
TestMeResume_Error:
b = 5
Resume
End Sub