我正在尝试使用VBA搜索范围内的字符串。我已经整理了一些代码,但是在“ If Not”这一行中不断出现1004错误:
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
关于我为什么会收到错误的任何想法?
答案 0 :(得分:3)
我对双.Find
感到困惑
如果您的Range.Find
方法已经返回了一个Range
对象一次,则无需设置两次。
另外search_range
已经是一个Range
对象,因此需要尝试将其封装在另一个Range()
对象中。
的类型中需要一个字符串
实际上是原因,您遇到了错误,因为它 在类型为Range(<string>)
@MathieuGuindon正确指出:
这是错误的原因,但是原因是因为 不合格的范围调用是
ActiveSheet
的子对象 是,并且您无法执行Sheet1.Range(Sheet2.Cells(1, 1)
,Sheet2.Cells(1,> 10))
-OP的代码中引发错误1004,因为ws不是ActiveSheet
;使用ws限定Range调用会修复 也是错误的...但是Range(someRange
)肯定是多余的。
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
答案 1 :(得分:0)
您可以使用:
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
注意: