Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA: Returning Range.Find() result from a function

Tags:

object

excel

vba

I need to encapsulate Range.Find() in a function, so I have the following (R1, C1 etc are all defined consts):

Function FindData(FindWhat As Variant) As Range
    Dim TheR As Range
    Set TheR = Range(Cells(R1, C1), Cells(R2, C2)).Find(FindWhat, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext)
    FindData = TheR
End Function

I'm passing in a string, so the call is e.g.:

Set FirstCell = Call FindData("MyValue")

VBA pukes on the line FindData = TheR with the message Object variable or With block variable not set. I've tried adding this if-block:

If (TheR Is Nothing) Then
    FindData = Nothing
Else
    FindData = TheR
End If

but it doesn't make any difference. How can I return the value that Find() gives me?

like image 909
skiaddict1 Avatar asked Aug 09 '26 05:08

skiaddict1


1 Answers

For object variables, you need to add the Set keyword, even in functions! ;)

So just add that at the end :

Function FindData(FindWhat As Variant) As Range
    Dim TheR As Range
    Set TheR = Range(Cells(R1, C1), Cells(R2, C2)).Find(FindWhat, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext)
    Set FindData = TheR
End Function

And when you use the Call you won't get an output from the function, so you need to use parenthesis :

Set FirstCell = FindData("MyValue")
like image 131
R3uK Avatar answered Aug 12 '26 04:08

R3uK