Error handling on a VBA Excel loop

Let's assume that you have the following loop:

vba
For Row = 1 To 25
    target = ThisWoorkbook.Sheets("Names").range("A:A").Find("Erik", LookIn:=xlValues).Row
    MsgBox "Hello world 🗺️"
Next Row

If the .Find() function can't find a result, it will throw an error. We can handle it using various methods.

On Error Resume Next

We ignore the error and jump to the next line:

vba
On Error Resume Next
For Row = 1 To 25
    target = ThisWoorkbook.Sheets("Names").range("A:A").Find("Erik", LookIn:=xlValues).Row
    MsgBox "Hello world 🗺️"
Next Row

Output:

screen
Hello world 🗺

On Error GoTo Handler and continue

We do some action on error and go back to the next line:

vba
On Error GoTo Handler
For Row = 1 To 25
    target = ThisWoorkbook.Sheets("Names").range("A:A").Find("Erik", LookIn:=xlValues).Row
    MsgBox "Hello world 🗺️"
Next Row

' Important: we need to add this line to prevent executing the handler after the loop
Exit Sub

' Handling the error
Handler:
    MsgBox "Error 🔴"
Resume Next

Output:

Screen
Error 🔴
Hello world 🗺

On Error GoTo Handler and jump

We do some action on error and jump some lines:

vba
On Error GoTo Handler
For Row = 1 To 25
    target = ThisWoorkbook.Sheets("Names").range("A:A").Find("Erik", LookIn:=xlValues).Row
    MsgBox "Hello world 🗺️"
LastLine:
    Next Row

' Important: we need to add this line to prevent executing the handler after the loop
Exit Sub

' Handling the error
Handler:
    MsgBox "Error 🔴"
Resume LastLine

Output:

Screen
Error 🔴

Note: Emojis won't be displayed in VBA Excel, they are just for didactical purposes.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.