所以我正在开发一个像普通VLOOKUP一样工作的函数,但它将循环并返回多个值。我现在的问题是,我不确定如何使以下代码输出多个值WITH分隔符。 (即"结果1,结果2,结果3和#34;)如果有更简单的方法/解决我在这里的问题,我会接受建议。
Function KVLOOKUP(LookedValue As Variant, Matrix As Variant, Column As Integer) As Variant
Dim Result() As Integer
Dim i As Integer
Dim Counter As Long
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)
End If
Next i
On Error GoTo 0
If Counter = 0 Then
KVLOOKUP = CVErr(xlErrNA)
Else
KVLOOKUP = Insert command to add separator and output values here.
End If
End Function
答案 0 :(得分:0)
这是一种方法。它基本上循环遍历Results数组,并构建一个以逗号分隔的字符串值,该值将被转储出去。我没有彻底测试这一切,所以你应该计划进行一些错误检查,但希望它会让你走向正确的方向:
Function KVLOOKUP(LookedValue As Variant, Matrix As Variant, Column As Integer) As Variant
Dim Result() As Variant
Dim i As Integer
Dim Counter As Long
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)
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