How to pass in a Range parameter for VLookup function?
Frage
I have the two functions below in VBA. The abb00
works fine but the abb11
does not.
My question is how to pass in a Range
variable as a parameter for VLookup
function?
Function abb00() 'demo func
abb00 = Application.WorksheetFunction.VLookup("a", _
Worksheets("SheetCache").Range("A:B"), 2, False)
End Function
Function abb11() 'demo func
rangeVar = Worksheets("SheetCache").Range("A:B")
abb11 = Application.WorksheetFunction.VLookup("a", rangeVar, 2, False)
End Function
Lösung
You can do this in two ways
Fixing your Function
Your current Function is not setting a range variable. It will work like this
Function abb11()
Dim rangeVar as Range
Set rangeVar = Worksheets("SheetCache").Range("A:B")
abb11 = Application.WorksheetFunction.VLookup("a", rangeVar, 2, False)
End Function
Passing a Range to your Function
Alternatively you can pass a range to the Function like this
Sub GetRange()
Dim rangeVar As Range
Set rangeVar = Worksheets("SheetCache").Range("A:B")
MsgBox abb2(rangeVar)
End Sub
Function abb2(ByVal rangeVar)
abb2 = Application.WorksheetFunction.VLookup("a", rangeVar, 2, False)
End Function
Andere Tipps
To pass a range, you first need to get a reference to a range.
You currently have this:
rangeVar = Worksheets("SheetCache").Range("A:B")
This doesn't get a range; it reads the entire range A:B
into a Variant array. If you want to get a range reference, you need to use the Set
keyword.
Set rangeVar = Worksheets("SheetCache").Range("A:B")
Ironically this doesn't impact the output of your abb11
function (EDIT: in Excel 2003), because VLookup
can be applied to a Variant array as well as to a Range. However, reading two whole columns into an array is rather inefficient, so I would stick to getting a range reference (Set rangeVar = ...
). EDIT In Excel 2007/2010, reading two entire columns into a Variant array will probably cause your function to die, because there are a million rows to load as opposed to 65536 in Excel 2003, which is what I was testing.