首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >未找到任何内容时,Excel宏搜索以错误结束

未找到任何内容时,Excel宏搜索以错误结束
EN

Stack Overflow用户
提问于 2013-10-03 12:36:06
回答 2查看 3.8K关注 0票数 0

我的案例1只要搜索找到数据,excel宏代码就会运行,但当搜索结果中没有任何内容时,就会报错。所以我试着放入一个“套装”见案例2..。但这个案子在任何搜索中都会失败。

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

代码语言:javascript
复制
 Cells.Find(What:=sCurrentISOtext & "_", After:=ActiveCell, _
            LookIn:=xlFormulas, LookAt :=xlWhole , _
           SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
            MatchCase:= False, SearchFormat:=False).Activate

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

代码语言:javascript
复制
  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':未设置对象变量或块变量

代码语言:javascript
复制
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 
EN

回答 2

Stack Overflow用户

发布于 2013-10-03 13:10:32

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

代码语言:javascript
复制
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
票数 4
EN

Stack Overflow用户

发布于 2015-10-30 09:55:15

这是我在匆忙中使用的一个丑陋的解决方案--有更优雅的错误陷阱,但它可以完成它。

代码语言:javascript
复制
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.                  <<
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19150868

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档