Let's assume that you have the following loop:
vbaFor 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.
We ignore the error and jump to the next line:
vbaOn 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:
screenHello world 🗺
We do some action on error and go back to the next line:
vbaOn 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:
ScreenError 🔴 Hello world 🗺
We do some action on error and jump some lines:
vbaOn 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:
ScreenError 🔴
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.