Home » excel » Excel formula or database lookup for mapping multi-valued cell to multi-valued result?

Excel formula or database lookup for mapping multi-valued cell to multi-valued result?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have two worksheets in Excel.

One is a mapping, for example

A Aardvark
B Bear
C Cow
D Dog

The other is a table whose 2nd column I want to complete automatically. The first column contains single values, or multiple values comma-separated:

A
A, C
D, B
C

The result I want in the 2nd column is

Aardvark
Aardvark, Cow
Dog, Bear
Cow

As long as 1st column cells contain only single values, it’s easy with Excel VLOOKUP.

But it doesn’t handle multiple values (or rather, it misunderstands them as single values) and gives result

Aardvark
#NA
#NA
Cow

How can I get the desired result? Perhaps with more complex formula, different Excel function, array tables, or using MS-SQL client in Excel to query the Excel tables as a database?

How to&Answers:

UDF approach:

Function MultiVL(v As Range, tbl As Range)

    Dim arr, rv As String, x As Integer, res

    rv = ""
    arr = Split(v.Value, ",")
    For x = LBound(arr) To UBound(arr)
        res = Application.VLookup(Trim(arr(x)), tbl, 2, False)
        rv = rv & IIf(rv <> "", ", ", "") & IIf(IsError(res), "?", res)
    Next x

    MultiVL = rv

End Function