简体   繁体   中英

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.

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. 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.

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 :

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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