我想编写一个vba函数,它将一个范围参数作为输入,并输出匹配的单元格。
Function find_cell_range(slct As Range, ByVal search_name As String) As Range
Dim rg As Range
With Range(slct)
Set rg = .Find(What:=search_name, LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)
End With
Set find_cell_range = rg
End Function
Sub test_sub()
Dim rg as Range
rg = find_cell_range(Range("A1", Range("A1").End(xlToRight)), "Col1")
'Some code which uses Range variable rg
End Sub
有了这个,我有时会出现Run-time error '1004': Method 'Range' of object '_Global' failed
错误。我应该如何成功通过我的函数中可以使用的范围?
答案 0 :(得分:1)
Range()
接受单个字符串A1引用或2个单元格范围/字符串地址。
Function find_cell_range(slct As Range, ByVal search_name As String) As Range
Set find_cell_range = slct.Find(What:=search_name, LookAt:=xlWhole, MatchCase:=True, SearchFormat:=False)
End Function
Sub test_sub()
Dim rg as Range
rg = find_cell_range(Range("A1", Range("A1").End(xlToRight)), "Col1")
If Not rg Is Nothing Then
'Some code which uses Range variable rg
End If
End Sub
答案 1 :(得分:0)
您的代码没有任何问题。你应该把它称为,
Set rg = find_cell_range(Range("A1", Range("A1").End(xlToRight)), "Col1")
答案 2 :(得分:0)
您必须使用 设置 :
<强> UNTESTED 强>:
Sub test_sub()
Dim rg as Range
Set rg = find_cell_range(Range("A1", Range("A1").End(xlToRight)), "Col1")
'Some code which uses Range variable rg
End Sub
答案 3 :(得分:0)
我不明白为什么你在函数中调用函数。只需使用:
Sub Test()
Dim rg As Range
Dim LastRow As Long
Dim sht As Worksheet
Set sht = Worksheets("Tabelle1")
LastRow = sht.Cells(sht.Rows.Count, 1).End(xlUp).Row
Set rg = sht.Range("A1:A" & LastRow).Find("Col1")
End Sub
现在,您可以按照自己的功能解决rg
问题。
答案 4 :(得分:0)
如果符合您的要求,您可以使用其编号来捕获错误:
Sub test_sub()
Dim rg As Range
On Error Resume Next
Set rg = find_cell_range(Range("A1", Range("A1").End(xlToRight)), "Col1")
If Err.Number = 1004 Then
MsgBox "Set range returns an error!"
'you can exit sub, set a new range, or goto anywhere in your code
End If
'Some code which uses Range variable rg
End Sub