繁体   English   中英

使用VBA在MS Excel中查找范围内的值

[英]Find a value from a range in MS Excel using VBA

有人可以指出以下代码在哪里出问题了。 我需要在使用find命令的范围内查找某个值的所有出现。 为了开始查找下一个事件,我在第一个找到的单元格之后再次使用find命令。 但是,用于调试目的的消息框显示第二个find命令也引用了相同的第一个找到的单元格,因为这两个命令的单元格地址都与输出相同。

有人可以指出这是什么错误。 我已经花了一天的时间,但仍然无法找出错误。

提前致谢。

Set FoundCell = Range("Act_No").Find(what:=PreActivityArray(i))
If Not FoundCell Is Nothing Then
    firstaddress = FoundCell.Address
    Do
        MsgBox (CStr(FoundCell) & " address " & CStr(FoundCell.Address) & " " & CStr(FoundCell.Row))
        Set FoundCell = Range("Act_No").Find(what:=PreActivityArray(i), after:=FoundCell)
        MsgBox (CStr(FoundCell) & "address " & CStr(FoundCell.Address) & " " & CStr(FoundCell.Row))
    Loop While Not FoundCell Is Nothing And FoundCell.Address <> firstaddress
End If

改用FindNext方法:

Set FoundCell = Range("Act_No").Find(What:=PreActivityArray(i))
If Not FoundCell Is Nothing Then
    firstaddress = FoundCell.Address
    Do
        MsgBox FoundCell & " address " & FoundCell.Address & " " & FoundCell.Row
        Set FoundCell = Range("Act_No").FindNext(FoundCell)
        If FoundCell Is Nothing Then Exit Do
        If FoundCell.Address = firstaddress Then Exit Do
        MsgBox "Another instance of value: " & FoundCell.Address
    Loop While True
End If

还要注意,我正在使用If FoundCell Is Nothing Then Exit Do
您不能像原始代码中那样在Loop While Not FoundCell Is Nothing And FoundCell.Address <> firstaddress使用Loop While Not FoundCell Is Nothing And FoundCell.Address <> firstaddress行,因为如果FoundCellNothingFoundCell.Address会触发运行时错误。

您也可以阅读以下内容: Excel VBA中的.Find和.FindNext

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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