0

只要搜索找到数据,我的案例 1 excel 宏代码就会运行,但是当搜索结果中没有任何内容时,会出现所述错误。因此,我尝试放入一个“集合”,参见案例 2……但该案例在任何搜索中都会爆炸。

案例 1:运行时错误“91”:对象变量或未设置块变量

 Cells.Find(What:=sCurrentISOtext & "_", After:=ActiveCell, _
            LookIn:=xlFormulas, LookAt :=xlWhole , _
           SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
            MatchCase:= False, SearchFormat:=False).Activate

案例 2:运行时错误“424”:需要对象

  Dim c As Range 

  Set c = Cells.Find(What:=sCurrentISOtext & "_", After:=ActiveCell, _
                     LookIn:=xlFormulas, LookAt :=xlWhole, _
                     SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
                     MatchCase:= False, SearchFormat:=False).Activate

你的意思是这样??它仍然失败。

案例 3:运行时错误“91”:对象变量或未设置块变量

Dim c As Range      

c = Cells.Find(What:=sCurrentISOtext & "_", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole = 0, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase _
        :=False, SearchFormat:=False)

If Not c Is Nothing Then   
    c.Activate     
    ' and do something here < > 
End If 
4

2 回答 2

4

这自然会失败,您在空(失败)结果上调用“激活” - 所以在运行时没有什么可以激活的。您必须包含一个 If 语句 -

Dim c As Range

Set c = Cells.Find(What:=sCurrentISOtext & "_", _
                   After:=ActiveCell, _
                   LookIn:=xlFormulas, _
                   LookAt:=xlWhole = 0, _
                   SearchOrder:=xlByColumns, _
                   SearchDirection:=xlNext, _
                   MatchCase:= False, _
                   SearchFormat:=False)

If c Is Nothing Then
    'do something
Else
    c.Activate
End If
于 2013-10-03T05:10:31.513 回答
-1

这是我在赶时间时使用的一个丑陋的解决方法——有更优雅的错误陷阱,但这可以完成。

On Error GoTo notFound
Dim c As Range

Set c = Cells.Find(What:=sCurrentISOtext & "_", _
                   After:=ActiveCell, _
                   LookIn:=xlFormulas, _
                   LookAt:=xlWhole = 0, _
                   SearchOrder:=xlByColumns, _
                   SearchDirection:=xlNext, _
                   MatchCase:=False, _
                   SearchFormat:=False)
c.Activate
Exit Sub

notFound:

Application.InputBox "Could not find the range you wanted." 
' >> You can put in whatever action you want here -- for example,        <<
' >> if you're using this as a module, then "Exit Sub" or "Goto nextOne" <<
' >> could be used go to the next step in your process.                  <<
于 2015-10-30T01:55:14.940 回答