简体   繁体   中英

Why am I getting an error with Find in VBA?

I'm trying to search for a string in a range using VBA. I've cobbled together some code but I keep getting a 1004 error at the "If Not" line:

Sub test1()

Dim wb As Workbook
Dim ws As Worksheet
Dim found_range As Range
Dim search_range As Range

Set wb = Workbooks("D1")
Set ws = wb.Sheets("Master data")

Set search_range = ws.Cells(147, 1).EntireRow

If Not Range(search_range).Find("Test") Is Nothing Then
    'match found
    Set found_range = Range(search_range).Find("Test")
    Debug.Print found_range.Column
Else
    MsgBox "No match found"
    'no match found
End If

End Sub

Any ideas as to why I'm getting the error?

I'm kind of confused with the double .Find
If your Range.Find method already returns a Range object once, there's no need to set it twice.

Also search_range is already a Range object, so need to try to encapsulate it in another Range() object.

In fact it's the reason, you are getting the error, because it expects a string inside the type-casted Range(<string>)

As @MathieuGuindon correctly pointed out:

It is the cause of the error, but the reason is because the unqualified Range call is a child object of whatever the ActiveSheet is, and you can't do Sheet1.Range(Sheet2.Cells(1, 1) , Sheet2.Cells(1,> 10)) - error 1004 is thrown in OP's code because ws isn't the ActiveSheet ; qualifying the Range call with ws would have fixed the error too... but yeah Range(someRange ) is definitely redundant.

Sub test1()

  Dim wb As Workbook
  Dim ws As Worksheet
  Dim found_range As Range
  Dim search_range As Range

  Set wb = Workbooks("D1")
  Set ws = wb.Sheets("Master data")

  Set search_range = ws.Cells(147, 1).EntireRow
  Set found_range = search_range.Find("Test")

  If Not found_range Is Nothing Then
      Debug.Print found_range.Address
  Else
      MsgBox "No match found"
  End if

End Sub

You could use:

Option Explicit

Sub test1()

    Dim wb As Workbook
    Dim ws As Worksheet
    Dim found_range As Range, search_range As Range

    Set wb = Workbooks("D1")
    Set ws = wb.Sheets("Master data")

    Set search_range = ws.Rows(147).EntireRow
    Set found_range = search_range.Find(What:="Test", LookIn:=xlValues, LookAt:=xlWhole)

    If Not found_range Is Nothing Then

        Debug.Print found_range.Column

    Else
        MsgBox "No match found"
        'no match found
    End If

End Sub

Note:

  • i you want exact match you should use LookAt:=xlWhole

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