Excel - 如何查找以返回多个值?

ove*_*lew 22 vlookup microsoft-excel

我希望使用 Excel 查找并返回给定键的多个参考值。VLookup做了一些与我需要的非常相似的事情——但只返回一个匹配项。

我认为它会涉及数组返回和处理方法,尽管我之前没有处理过这些。一些谷歌搜索开始依赖 if([lookuparray]=[value],row[lookuparray]) 作为解决方案的一部分 - 尽管我无法让它返回单个匹配......

例如,如果我有这个参考数据:

Adam    Red
Adam    Green
Adam    Blue
Bob     Red
Bob     Yellow
Bob     Green
Carl    Red 
Run Code Online (Sandbox Code Playgroud)

我正在尝试获取右侧的多个返回值。(如果可能,逗号分隔)

Red      Adam, Bob, Carl
Green    Adam, Bob
Blue     Adam
Yellow   Bob
Run Code Online (Sandbox Code Playgroud)

(我已经有了左边的键值 - 不需要拉出这些值)

关于如何在此上下文中处理多个值的任何帮助表示赞赏。谢谢。

Dan*_*Dan 14

假设您想要如上所述的公式方法(不使用 VLOOKUP,但仍然是一个公式),以下是我布置数据的方式:

数据布局

然后我在单元格 C12 中使用了以下公式:

=INDEX($C$2:$C$8, SMALL(IF($B12=$B$2:$B$8, ROW($B$2:$B$8)-MIN(ROW($B$2:$B$8))+1, ""), 1))
Run Code Online (Sandbox Code Playgroud)

这是一个数组公式,因此在您将其复制并粘贴到单元格中后,您必须点击Ctrl+Shift+Enter。然后我只是把它拖到右边和底部。

如果没有剩余的值,它会给出#NUM!错误,我在上传的图像示例中给出了一个黄色示例。

如果您有大量行,我认为 VBA/宏方法将是更好的解决方案。


Eng*_*ast 6

这是适合您的 VBA 解决方案。首先,这是结果的样子:

截屏

这是代码:

Option Explicit
Function LookupCSVResults(lookupValue As Variant, lookupRange As Range, resultsRange As Range) As String

    Dim s As String 'Results placeholder
    Dim sTmp As String  'Cell value placeholder
    Dim r As Long   'Row
    Dim c As Long   'Column
    Const strDelimiter = "|||"  'Makes InStr more robust

    s = strDelimiter
    For r = 1 To lookupRange.Rows.Count
        For c = 1 To lookupRange.Columns.Count
            If lookupRange.Cells(r, c).Value = lookupValue Then
                'I know it's weird to use offset but it works even if the two ranges
                'are of different sizes and it's the same way that SUMIF works
                sTmp = resultsRange.Offset(r - 1, c - 1).Cells(1, 1).Value
                If InStr(1, s, strDelimiter & sTmp & strDelimiter) = 0 Then
                    s = s & sTmp & strDelimiter
                End If
            End If
        Next
    Next

    'Now make it look like CSV
    s = Replace(s, strDelimiter, ",")
    If Left(s, 1) = "," Then s = Mid(s, 2)
    If Right(s, 1) = "," Then s = Left(s, Len(s) - 1)

    LookupCSVResults = s 'Return the function

End Function
Run Code Online (Sandbox Code Playgroud)


F10*_*art 5

  1. 交换列,使颜色在 A 列中,名称在 B 列中,然后按颜色排序。

  2. C2 中的公式(将其复制到列中):=IF(A2<>A1,B2,C1 & ", " & B2)

  3. D2 中的公式(将其复制到列中):=A2<>A3

  4. 在 D 列过滤“TRUE”以获得所需的结果。见下文:

在此处输入图片说明