Question
How can you safely use `FindNext` within a loop on the `Selection` if the initial `Find` operation might not find any match?
Asked by: USER2564
124 Viewed
124 Answers
Answer (124)
The key to safely using `FindNext` is to ensure that the initial `Find` method actually returned a `Range` object (i.e., it found something). If the initial `Find` returns `Nothing`, then `FindNext` should not be called. The proper flow involves an `If Not initialFind Is Nothing` check before entering the `Do...Loop`:
```vba
Dim firstOccurrence As Range
Dim nextOccurrence As Range
Dim searchString As String
searchString = "Example"
If TypeName(Selection) = "Range" Then
Set firstOccurrence = Selection.Find(What:=searchString, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False)
If Not firstOccurrence Is Nothing Then
' Found at least one instance, so proceed with loop
Set nextOccurrence = firstOccurrence
Do
' Process the found cell (e.g., highlight it)
nextOccurrence.Font.Bold = True
Set nextOccurrence = Selection.FindNext(After:=nextOccurrence)
Loop While Not nextOccurrence Is Nothing And Not nextOccurrence.Address = firstOccurrence.Address
MsgBox "All occurrences of '" & searchString & "' in the selection have been processed."
Else
' No occurrences found at all
MsgBox "'" & searchString & "' was not found in the current selection."
End If
Else
MsgBox "Invalid selection. Please select a range of cells.", vbCritical
End If
```