VBA发现问题 - 当没有发现错误
问题描述:
我敢打赌,这是简单的。即使我已经研究了很多,并尝试了几种方法,但仍然出现运行时错误424.VBA发现问题 - 当没有发现错误
代码是查找用户输入的数字。如果数字在数据集中,我想做一件事,但如果数字不在数据集中,我想做其他事情。
代码如下。
Sub Test()
Dim Material As String
Dim cell As Range
Material = InputBox("Enter BIS # for material type")
Range("A7:a40").Select
Set cell = Selection.Find(What:=Material, After:=ActiveCell, LookIn:=xlFormulas, LookAt:= _xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _, SearchFormat:=False).Activate
If cell Is Nothing Then
MsgBox "Boo"
Else
MsgBox "Great"
End If
End Sub
答
不能调用Activate
如果Find
回报什么,这样会导致错误。此外,Activate
是一个子函数,而不是函数,所以您不能将cell
设置为其返回值。
注意:有没有必要Select
的Range("A7:A40")
为Find
功能工作。您可以完全限定的Find
功能是通过Range("A7:A40").Find...
搜索的特定值的Range
试试这个:
Sub Test()
Dim Material As String
Dim cell As Range
Material = InputBox("Enter BIS # for material type")
Set cell = Range("A7:A40").Find(What:=Material, LookIn:=xlValues, LookAt:=xlWhole, _
SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
If cell Is Nothing Then ' <-- this lines checks if Find failed to find a match
MsgBox "Boo"
Else
cell.Activate
MsgBox "Great"
End If
End Sub
不错,我已经编辑你的答案,因为没有必要'Select'查找功能的'范围'工作 –
有时选择是用户体验的一部分,所以我没有碰它。但我确定OP可以弄清楚你做了什么,现在他们有了选择。 –
工程就像一个魅力。非常感谢! –