Excel UDF-在单个单元格中具有部分匹配和连接结果的VLOOKUP

时间:2019-03-27 13:07:49

标签: excel vba user-defined-functions

我有2列数据和第三列查询字词。查询字词在数据列1(“ Data1”)中具有部分但完全匹配的条件。我想在“ Data1”列中找到查询词的所有匹配项,并从“ Data2”列中返回逗号分隔的值。

请查看图片。

此网站上已经存在针对类似问题的UDF,但这并不能完全满足我的要求。

Excel: Return multiple matches in a single cell while doing a partial match

非常感谢您的帮助。祝福马诺伊Data Image

我已经尝试过这个UDF:

Public Function ConcatPartLookUp(rngInput As Range, rngSource As Range, Optional strDelimiter As String, Optional blCaseSensitive)
Dim rng As Range

If strDelimiter = "" Then strDelimiter = "|"
If IsMissing(blCaseSensitive) Then
    blCaseSensitive = False
Else
    blCaseSensitive = True
End If

For Each rng In rngSource
    If blCaseSensitive Then
        If InStr(1, rng.Value, rngInput.Value, vbBinaryCompare) > 0 Then ConcatPartLookUp = ConcatPartLookUp & strDelimiter & rng.Value
    Else
        If InStr(1, rng.Value, rngInput.Value, vbTextCompare) > 0 Then ConcatPartLookUp = ConcatPartLookUp & strDelimiter & rng.Value
    End If
Next

If Len(ConcatPartLookUp) > 0 Then ConcatPartLookUp = Mid(ConcatPartLookUp, 2, Len(ConcatPartLookUp))

End Function

此代码将返回“ Data1”列中的匹配项(非常蓝天。|永远蓝天)。我想在Data1上匹配,但从Data2返回值。 谢谢

1 个答案:

答案 0 :(得分:0)

如果您具有Office 365 Excel,则可以将TEXTJOIN用作数组公式:

 =TEXTJOIN(",",TRUE,IF(ISNUMBER(SEARCH(D2,$A$2:$A$6)),$B$2:$B$6,""))

作为数组公式,退出编辑模式时需要使用Ctrl-Shift-Enter而不是Enter进行确认。


如果没有Office 365,则将此代码放在模块中,然后使用上述公式:

Function TEXTJOIN(delim As String, skipblank As Boolean, arr)
    Dim d As Long
    Dim c As Long
    Dim arr2()
    Dim t As Long, y As Long
    t = -1
    y = -1
    If TypeName(arr) = "Range" Then
        arr2 = arr.Value
    Else
        arr2 = arr
    End If
    On Error Resume Next
    t = UBound(arr2, 2)
    y = UBound(arr2, 1)
    On Error GoTo 0

    If t >= 0 And y >= 0 Then
        For c = LBound(arr2, 1) To UBound(arr2, 1)
            For d = LBound(arr2, 1) To UBound(arr2, 2)
                If arr2(c, d) <> "" Or Not skipblank Then
                    TEXTJOIN = TEXTJOIN & arr2(c, d) & delim
                End If
            Next d
        Next c
    Else
        For c = LBound(arr2) To UBound(arr2)
            If arr2(c) <> "" Or Not skipblank Then
                TEXTJOIN = TEXTJOIN & arr2(c) & delim
            End If
        Next c
    End If
    TEXTJOIN = Left(TEXTJOIN, Len(TEXTJOIN) - Len(delim))
End Function