VLookup VBA函数始终返回空字符串

时间:2018-10-18 08:46:03

标签: excel vba excel-vba

我的VBA功能有问题 Application.WorksheetFunction.VLookup始终返回一个空字符串, 我尝试使用硬编码参数,其结果相同。

Public Function SeqVlookup(ByVal target As String, vrange As Range, vcol As Long)

    Dim WrdArray() As Variant  
    Dim text_string As Variant  


    text_string = target

    WrdArray() = Split(text_string,",")  

    Dim vlookupArray(0 To UBound(WrdArray)) As Variant  


    On Error Resume Next
    For i = 0 To UBound(WrdArray)  

      vlookupArray(i) = Application.WorksheetFunction.VLookup(WrdArray(i), vrange, vcol, 0)


    Next i  

      SeqVlookup = Join(vlookupArray, ",")
      MsgBox Join(vlookupArray, ",") 

End Function

初始化命令

   =SEQVLOOKUP(1,Sheet2.A:B,2)

2 个答案:

答案 0 :(得分:0)

以下代码似乎有效。请注意,Split需要填充String数组。 VLOOKUP无法正常工作的可能原因是查找键是字符串,范围内的值可能是数字?下面的代码会同时尝试两者。

Public Function SeqVlookup(ByVal target As String, vrange As Range, vcol As Long) As Variant

    Dim WrdArray() As String
    Dim vlookupArray() As Variant

    WrdArray = Split(target, ",")

    ReDim vlookupArray(LBound(WrdArray) To UBound(WrdArray))

    Dim i As Long

    On Error Resume Next
    For i = LBound(WrdArray) To UBound(WrdArray)
        vlookupArray(i) = WorksheetFunction.VLookup(WrdArray(i), vrange, vcol, False)

        If IsEmpty(vlookupArray(i)) Then
            If IsNumeric(WrdArray(i)) Then
                vlookupArray(i) = WorksheetFunction.VLookup(CLng(WrdArray(i)), vrange, vcol, False)
            End If
        End If
    Next i
    On Error GoTo 0

    SeqVlookup = Join(vlookupArray, ",")
    MsgBox Join(vlookupArray, ",")

End Function

答案 1 :(得分:0)

我发现了问题,现在可以解决问题

Option VBASupport 1

Public Function SeqVlookup(ByVal target As String, vSheet As String, vrange As String, vcol As Long) As Variant
Dim WrdArray() As String
   Dim vlookupArray() As Variant
   WrdArray = Split(target, ",")

   If UBound(WrdArray) = -1  Then 
        SeqVlookup = ""
   Else
       ReDim vlookupArray(LBound(WrdArray) To UBound(WrdArray))
       Dim i As Long
       Dim thisRange  As String
       thisRange = vrange
       Dim thisSheet  As String
       thisSheet = vSheet
       On Error Resume Next
       For i = LBound(WrdArray) To UBound(WrdArray)
            Dim thisVal  As Integer
            thisVal = WrdArray(i)
            vlookupArray(i) = WorksheetFunction.VLookup(thisVal, Worksheets(thisSheet).Range(thisRange), vcol, False)
       Next i
       On Error GoTo 0
       SeqVlookup = Join(vlookupArray, ",")
    End If   
End Function

= SEQVLOOKUP(C2,“ sheet2”,“ A:B”,2)