You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel中用VLOOKUP获取多匹配结果的方法咨询

用VBA宏获取重复查询值的所有匹配结果

当第一列存在重复值时,VLOOKUP只能返回第一个匹配的结果,要获取所有对应的值,完全可以通过VBA宏实现,下面是两种实用的实现方式:

方式一:自定义函数(直接在单元格调用,返回合并后的结果)

这种方式可以像内置函数一样使用,把所有匹配结果用指定分隔符合并到单个单元格中。

操作步骤:

  1. 打开Excel,按下 Alt + F11 打开VBA编辑器
  2. 在左侧工程窗口中,右键点击你的工作簿名称,选择「插入」→「模块」
  3. 将以下代码粘贴到模块窗口中:
Function GetAllMatches(lookupVal As Variant, lookupRange As Range, resultRange As Range, Optional delimiter As String = ", ") As String
    Dim cell As Range
    Dim result As String
    Dim i As Integer
    
    ' 确保查找范围和结果范围行数一致
    If lookupRange.Rows.Count <> resultRange.Rows.Count Then
        GetAllMatches = "范围行数不匹配"
        Exit Function
    End If
    
    For i = 1 To lookupRange.Rows.Count
        If lookupRange.Cells(i, 1).Value = lookupVal Then
            If result <> "" Then
                result = result & delimiter
            End If
            result = result & resultRange.Cells(i, 1).Value
        End If
    Next i
    
    GetAllMatches = result
End Function
  1. 关闭VBA编辑器,回到Excel工作表

使用方法:

在任意空白单元格中输入公式,比如要查询值21,A列为查询列,B列为结果列,输入:
=GetAllMatches(21,A:A,B:B)
或者指定分隔符为换行(适合单元格换行显示):
=GetAllMatches(21,A:A,B:B,CHAR(10))
按下回车后,就能得到所有匹配的结果(比如600, 650)


方式二:批量输出到多行的宏

如果希望把每个匹配结果单独输出到一行,可以用这个宏:

操作步骤:

  1. 同样打开VBA编辑器,插入新模块,粘贴以下代码:
Sub ExtractAllMatches()
    Dim lookupVal As Variant
    Dim lookupRange As Range
    Dim resultRange As Range
    Dim outputRange As Range
    Dim i As Integer
    Dim outputRow As Integer
    
    ' 设置查询值、查找范围、结果范围和输出起始位置
    lookupVal = 21 ' 可改为InputBox("请输入查询值:"),让运行时手动输入
    Set lookupRange = ThisWorkbook.Sheets("Sheet1").Range("A:A") ' 替换为你的查询列
    Set resultRange = ThisWorkbook.Sheets("Sheet1").Range("B:B") ' 替换为你的结果列
    Set outputRange = ThisWorkbook.Sheets("Sheet1").Range("D1") ' 替换为输出的起始单元格
    
    outputRow = 0
    For i = 1 To lookupRange.Rows.Count
        If lookupRange.Cells(i, 1).Value = lookupVal And Not IsEmpty(lookupRange.Cells(i, 1).Value) Then
            outputRange.Offset(outputRow, 0).Value = resultRange.Cells(i, 1).Value
            outputRow = outputRow + 1
        End If
    Next i
    
    MsgBox "共找到" & outputRow & "个匹配结果"
End Sub
  1. 修改代码中的查询值、范围和输出位置为你的实际需求
  2. 按下F5运行宏,或者回到Excel中通过「开发工具」→「宏」选择ExtractAllMatches运行

内容的提问来源于stack exchange,提问作者Ikigai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 10:15:38