繁体   English   中英

vba函数,将范围参数作为输入并返回范围

[英]vba function which takes a range parameter as input and returns a range

我想编写一个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错误。 如何成功传递可以在我的函数中使用的范围?

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

您的代码没有错。 你应该这样称呼它

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

您必须使用Set

未测试

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM