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

如何对Excel两列文本进行部分匹配并将匹配值返回到第三列

问题定位

你原有代码存在4处问题:

  • 匹配逻辑写反:InStr(1, s2, s1)是判断短的part_number是否包含长的完整文件名,完全不符合需求
  • 变量拼写错误:最终判断的WhereI是笔误,应为WhereIs
  • 分支逻辑写反:无匹配结果时才应该返回no match,原有代码逻辑刚好相反
  • 返回内容错误:需求是返回匹配的part_number值,原有代码返回的是单元格地址
修正后可直接使用的UDF代码
Public Function MatchPart(rFilename As Range, rPartList As Range) As String
    Dim sFilename As String, sPart As String, partCode As String
    Dim r As Range
    MatchPart = ""
    ' 读取待匹配的完整文件名
    sFilename = rFilename.Text
    
    For Each r In rPartList
        sPart = r.Text
        ' 跳过空单元格
        If sPart = "" Then GoTo NextLoop
        ' 提取part_number的核心编号(去掉.jpg后缀,不区分大小写)
        partCode = Replace(sPart, ".jpg", "", 1, -1, vbTextCompare)
        ' 判断核心编号是否存在于文件名中
        If InStr(1, sFilename, partCode, vbTextCompare) > 0 Then
            If MatchPart = "" Then
                MatchPart = sPart
            Else
                ' 多个匹配用逗号分隔
                MatchPart = MatchPart & "," & sPart
            End If
        End If
NextLoop:
    Next r
    
    ' 无匹配时返回提示
    If MatchPart = "" Then MatchPart = "no match"
End Function
使用方法
  1. 打开你的Excel文件,按Alt+F11调出VBA编辑器,右键点击你的工作簿名称,选择「插入」-「模块」,把上述代码粘贴到模块窗口中,保存文件为启用宏的工作簿(.xlsm格式)
  2. 假设你的all_filenames存放在A列(从A2开始),part_number存放在B列(从B2到B501),在需要返回匹配结果的单元格(比如C2)输入公式=MatchPart(A2,$B$2:$B$501),下拉填充到所有行即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:54:01