简体   繁体   English

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

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

I want to write a vba function which takes a range parameter as input and outputs the cell where it gets the match. 我想编写一个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

With this, I'm sometimes getting Run-time error '1004': Method 'Range' of object '_Global' failed error. 这样,有时会出现Run-time error '1004': Method 'Range' of object '_Global' failed错误。 How should I successfully pass the range that can be used in my function? 如何成功传递可以在我的函数中使用的范围?

Range() accepts either a single string A1 reference, or 2 cell Range/String address. 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

There is nothing wrong with your code. 您的代码没有错。 You should call it like, 你应该这样称呼它

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

You must use Set : 您必须使用Set

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

I dont understand why u are calling the function in a function. 我不明白为什么您要在函数中调用该函数。 Just use: 只需使用:

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

And now you can address rg like you want it from your function. 现在,您可以根据需要从功能中处理rg

You can catch the error using its number if that's what you want: 如果需要的话,可以使用错误编号来捕获错误:

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