[英]Why am I getting an error with Find in VBA?
I'm trying to search for a string in a range using VBA. 我正在尝试使用VBA搜索范围内的字符串。 I've cobbled together some code but I keep getting a 1004 error at the "If Not" line: 我拼凑了一些代码,但我在“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
Any ideas as to why I'm getting the error? 关于为什么我收到错误的任何想法?
I'm kind of confused with the double .Find
我有点混淆了.Find
If your Range.Find
method already returns a Range
object once, there's no need to set it twice. 如果Range.Find
方法已经返回一次Range
对象,则无需将其设置两次。
Also search_range
is already a Range
object, so need to try to encapsulate it in another Range()
object. search_range
也是一个Range
对象,因此需要尝试将其封装在另一个Range()
对象中。
In fact it's the reason, you are getting the error, because it expects a string inside the type-castedRange(<string>)
事实上,这是你得到错误的原因,因为它期望在类型转换Range(<string>)
内的Range(<string>)
As @MathieuGuindon correctly pointed out: 正如@MathieuGuindon正确指出:
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 doSheet1.Range(Sheet2.Cells(1, 1)
,Sheet2.Cells(1,> 10))
- error 1004 is thrown in OP's code because ws isn't theActiveSheet
; 它是错误的原因,但原因是因为非限定Range调用是ActiveSheet
的子对象,而你不能做Sheet1.Range(Sheet2.Cells(1, 1)
,Sheet2.Cells(1,> 10))
- 在OP的代码中抛出错误1004,因为ws不是ActiveSheet
; qualifying the Range call with ws would have fixed the error too... but yeahRange(someRange
) is definitely redundant. 使用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
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: 注意:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.