I'm having a problem defining a range on a separate sheet for an array that I have for a function that I'm running. The function is KVLOOKUP
and can be found here. The problem I'm having is when I try to set the Range in Sub Searched
it won't accept any type of defined range. I've tried what I can think of to define the range in different ways. Not sure where I'm going wrong here.
Function to be Called
Function KVLOOKUP(LookedValue As String, Matrix As Variant, Column As Integer) As Variant
Dim Result() As Variant
Dim i As Integer
Dim Counter As Long
Dim Column1 As Integer
Column1 = Column + 1
If IsObject(Matrix) Then Matrix = Matrix.Value
On Error Resume Next
Do
i = i + 1
Counter = UBound(Matrix, i)
Loop Until Err.Number <> 0
If Counter < Column Then KVLOOKUP = CVErr(xlErrNum): Exit Function
Counter = 0
For i = LBound(Matrix, 1) To UBound(Matrix, 1)
If Matrix(i, 1) = LookedValue Then
Counter = Counter + 1
ReDim Preserve Result(1 To Counter)
Result(Counter) = Matrix(i, Column) & " - " & Matrix(i, Column1)
End If
Next i
On Error GoTo 0
If Counter = 0 Then
KVLOOKUP = CVErr(xlErrNA)
Else
KVLOOKUP = Result(1)
For i = 2 To UBound(Result)
KVLOOKUP = KVLOOKUP & ", " & Result(i)
Next i
End If
End Function
My problem is within the code below. In a cell I can call KVLOOKUP
like a normal function =KVLOOKUP(TextToSearch,'IDBHour1'!B2:E120,2)
. When I have attempted to define the same range by calling the function within VBA I haven't been able to define the same range as above.
Sub to define E_name and Rnge Values
For some reason if I try to define the range like this (which is how it would be done for a normal VLookup function) it doesn't provide any results. This is how I've been going about debugging my issue.
When I run the code I get an "Object variable or With Block variable not set" error
Sub SearcherBox()
'E_name is just a name i.e., John Doe
'Rnge is the range in which KVLOOKUP is searching for "John Doe"
Dim Rnge as Range
Rnge = Sheets("IDBHour1").Range("B2:E120")
Sal = Application.WorksheetFunction.KVLOOKUP(E_name, Rnge, 2)
MsgBox Sal
End Sub