定义数组范围的问题

时间:2014-06-30 20:35:21

标签: vba excel-vba excel

我遇到了一个问题,在一个单独的工作表上为一个数组定义一个范围,我正在运行一个函数。该函数为KVLOOKUP,可以找到here。我遇到的问题是当我尝试在Sub Searched中设置范围时,它将不接受任何类型的已定义范围。我已经尝试了我能想到的以不同方式定义范围。不知道我在哪里错了。

要调用的功能

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

我的问题在下面的代码中。在单元格中,我可以像普通函数KVLOOKUP一样调用=KVLOOKUP(TextToSearch,'IDBHour1'!B2:E120,2)。当我试图通过调用VBA中的函数来定义相同的范围时,我无法定义与上面相同的范围。

Sub定义E_name和Rnge值

出于某种原因,如果我尝试定义这样的范围(对于正常的VLookup函数将如何进行),它不会提供任何结果。这就是我一直在调试我的问题。

当我运行代码时,我得到一个“对象变量或未设置块变量”错误

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

1 个答案:

答案 0 :(得分:1)

一些事情:

Rnge是一个对象变量。对象变量需要在赋值时使用Set关键字,所以

SET Rnge = Sheets("IDBHour1").Range("B2:E120")

此外,您的UDF KVLOOKUP不是WorksheetFunction,因此不是WOrksheetFunction类的成员,因此您在下一行也会收到错误。只需将您的UDF称为:

Sal = KVLOOKUP(E_name, Rnge, 2)