如何检测VBA excel是否发现了某些内容?

how to detect whether VBA excel found something?

提问人:Alex Gordon 提问时间:10/20/2009 更新时间:8/22/2023 访问量:42871

问:

我正在使用它在宏中查找我的工作表中的内容:

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

我怎么知道它是否发现了什么?

VBA Excel

评论


答:

3赞 Ryan Shannon 10/20/2009 #1

Find返回一个 Range 对象,如果未找到,该对象将保存值。从帮助:NothingWhat

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

评论

0赞 FreeSoftwareServers 3/9/2019
解释值是 if 语句没有找到任何真正帮助的东西,我正在测试变量是否与,但这不起作用!NOTHINGnullIsNull
18赞 manji 10/20/2009 #2
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

评论

1赞 FreeSoftwareServers 3/9/2019
读书让我头疼......您的评论有很大帮助!谢谢If Not rng Is Nothing Then
0赞 NickSentowski 10/20/2009 #3

Selection.Find 类似于使用 Ctrl+F 查找值。然后,您可以检查 Activecell.Value 以查看是否获得了所需的结果。

评论

0赞 BigBen 11/16/2023
Find不会更改ActiveCell.
-1赞 Naemoor 8/22/2023 #4

如果成功,Find 返回 TRUE,但如果不成功,则返回错误而不是 FALSE。所以。。。

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(“所选内容中存在的内容”, Range(Selection, Selection)) 真

?FoundIt(“房间里的大象”, Range(Selection, Selection)) 假

伊恩

评论

0赞 BigBen 11/16/2023
Find返回 ,而不是 .RangeBoolean