8

i am using this to in a macro to find stuff in my sheet:

Selection.Find(What:=email, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
    :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False).Activate

how can i tell whether or not it found something?

Alex Gordon
  • 57,446
  • 287
  • 670
  • 1,062

4 Answers4

18
Dim rng As Range

Set rng = Selection.Find(What:=email, After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
    False, SearchFormat:=False)

If Not rng Is Nothing Then 'when rng <> nothing means found something'
    rng.Activate
End IF
manji
  • 47,442
  • 5
  • 96
  • 103
3

Find returns a Range object that will ave value Nothing if What is not found. From the help:

With Worksheets(1).Range("a1:a500")
    Set c = .Find(2, lookin:=xlValues)
    If Not c Is Nothing Then
        firstAddress = c.Address
        Do
            c.Value = 5
            Set c = .FindNext(c)
        Loop While Not c Is Nothing And c.Address <> firstAddress
    End If
End With
Ryan Shannon
  • 710
  • 1
  • 5
  • 9
  • Explaining that the value is `NOTHING` if statement doesn't find anything really helps, I was testing if the variable was `null` with `IsNull` and that didn't work! – FreeSoftwareServers Mar 08 '19 at 20:42
1

Selection.Find is like using Ctrl+F to find a value. You can then check against Activecell.Value to see if you got the desired result.

NickSentowski
  • 820
  • 13
  • 27
0

Find returns TRUE if successful, but when unsuccessful it returns an error and not FALSE. So...

Public Function FoundIt(ByVal SearchFor As String _
                      , ByVal InHere As Range) As Boolean
                      
     FoundIt = False
     
     On Error Resume Next
     
     FoundIt = InHere.Find(What:=SearchFor _
                         , After:=ActiveCell _
                         , LookIn:=xlValues _
                         , LookAt:=xlPart _
                         , SearchOrder:=xlByRows _
                         , SearchDirection:=xlNext _
                         , MatchCase:=False _
                         , SearchFormat:=False).Activate

End Function

? FoundIt("Something in the Selection that exists", Range(Selection, Selection)) TRUE

? FoundIt("An Elephant in the Room", Range(Selection, Selection)) FALSE

Ian

Naemoor
  • 39
  • 5