简体   繁体   中英

Excel macro search for word on sheet

This is an easy one, but I can't get it to work. I need to search for the word "Tons" on a sheet.

Sub findText()

If Cells.Find(What:="Tons", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False).Activate = True Then
MsgBox "Word Found"
Else
MsgBox "Word Not Found"
End If

End Sub

I get the error "Object variable or With Block variable not set". My code works whenever the word "Tons" is on a sheet but comes back with an error whenever it is not. Thanks for the help.

Consider:

Sub findText()
Dim r As Range
Set r = Cells.Find(What:="Tons", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
        :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
        False, SearchFormat:=False)
If Not r Is Nothing Then
    MsgBox "Word Found"
Else
    MsgBox "Word Not Found"
End If

End Sub

Try to create a Range and then test if you succeeded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM