(Solved) – Error if nothing found when replacing a string (selection replace, find replace) Excel VBA

(solved)-–-error-if-nothing-found-when-replacing-a-string-(selection-replace,-find-replace)-excel-vba

This is the error I receive when running my macro. I thought I already addressed when the find function doesn’t find what I’m searching for by implementing an if statement. Somehow it’s still not working…

How can I skip the find/replace statement if the value I’m searching for doesn’t exist in my record?

enter image description here

My VBA Code:

Columns("D:D").Select
Set Example1 = Selection.Find(what:="Example One", LookIn:=xlFormulas, lookat:=xlPart, SearchOrder:=xlByRows)
If Not Example1 Is Nothing Then
Selection.Replace what:="Example One", Replacement:= _
    "Test One A", lookat:=xlPart, SearchOrder:=xlByRows _
    , MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False, _
    FormulaVersion:=xlReplaceFormula2
End If

Set Example2 = Selection.Find(what:="Example Two ", LookIn:=xlFormulas, lookat:=xlPart, SearchOrder:=xlByRows)
If Not Example2 Is Nothing Then
Selection.Replace what:="Example Two ", Replacement:= _
    "Test One B", lookat:=xlPart, SearchOrder:=xlByRows, MatchCase:= _
    False, SearchFormat:=False, ReplaceFormat:=False, FormulaVersion:= _
    xlReplaceFormula2
End If

Leave a Reply

Your email address will not be published. Required fields are marked *