简体   繁体   中英

Excel VBA find string : Error 2015

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.

Any ideas why I'm getting the error?

Thanks

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM