vba函数,它将范围参数作为input并返回一个范围

我想写一个vba函数,它将范围参数作为input,并输出匹配的单元格。

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错误。 我应该如何成功地通过我的function可以使用的范围?

Range()接受单个stringA1引用或2个单元格范围/string地址。

 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 

你的代码没有问题。 你应该这样称呼它,

 Set rg = find_cell_range(Range("A1", Range("A1").End(xlToRight)), "Col1") 

你必须使用Set

未经testing

 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 

我不明白为什么你在一个函数中调用函数。 只要使用:

 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

如果这是你想要的,你可以使用它的编号来捕捉错误:

 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