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

有人可以请指出我在哪里出错在下面的代码。 我需要查找所有在我使用find命令的范围内出现的值。 要开始查找下一个事件,我再次使用find命令,但在第一个find的单元格之后。 用于debugging目的的消息框表明,第二个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 ,因为如果您的原始代码是FoundCell ,那么FoundCell.Address触发运行时错误。

你也可以阅读这个: .Find和.FindNext在Excel VBA中