Excel VBA 查找字符串:错误 2015

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22014093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:51:52  来源:igfitidea点击:

Excel VBA find string : Error 2015

excelvbaexcel-vbafind

提问by Rueful Rabbit

I have to following code snippet ...

我必须遵循代码片段...

  Public Sub FindText(path As String, file As String)
    Dim Found As Range

    myText = "test("

    MacroBook = ActiveWorkbook.Name

    ' Open the File
    Workbooks.Open path & file, ReadOnly:=True, UpdateLinks:=False
    For Each ws In Workbooks(file).Worksheets
     With ws

       Set Found = .UsedRange.Find(What:=myText, LookIn:=xlFormulas, _
                      LookAt:=xlPart, MatchCase:=False)

       If Not Found Is Nothing Then
        ' do stuff
        ' ...

I see in the debugger that Found contains Error 2015! The sheet contains the text I want in the formula.

我在调试器中看到 Found 包含错误 2015!该工作表包含我想要在公式中的文本。

Any ideas why I'm getting the error?

任何想法为什么我收到错误?

Thanks

谢谢

回答by Dmitry Pavliv

As follow up from comments to the Q, Error 2015occurs because your formula in the sheet returns #VALUE!error. You can handle it using IsError:

从对 Q 的评论进行跟进,Error 2015因为工作表中的公式返回#VALUE!错误。您可以使用IsError以下方法处理它:

If Not Found Is Nothing Then
    If Not IsError(Found) Then
       ' do sth
    End If
End If

回答by Mat Richardson

You don't need to use 'Set' in your code. You only use this to assign a reference to an object. Try:-

您不需要在代码中使用“设置”。您仅使用它来分配对对象的引用。尝试:-

For Each ws In Workbooks(file).Worksheets
     With ws

       Found = .UsedRange.Find(What:=myText, LookIn:=xlFormulas, _
                      LookAt:=xlPart, MatchCase:=False)

       If Not Found Is Nothing Then
        ' do stuff
        ' ...

Hopefully this should work.

希望这应该有效。