Excel Vba 查询拼接函数

该博客介绍了两个VBA函数,CollectMatchInfo2和CollectMatchInfo,用于在指定区域查找匹配特定Code的行,并按指定分隔符拼接返回所有匹配项。函数考虑了参数校验、默认分隔符设置以及多列数据的处理,适用于Excel数据操作和检索场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 查询拼接函数一

'根据Code编码字符串,在Zone区域的第1列中查找匹配项,如果值等于Code 添加到返回内容里,返回所有的符合项。SplitorRow 查找到的行分隔符,SplitorRow 查到数据列之间的分隔符

参数:

    • Code :查询的内容
    • Zone :查询的区域
    • Splitor :行分隔符
    • SplitorRow :列分隔符


Function CollectMatchInfo2(Code As range, Zone As range, Splitor As String, SplitorRow As String)
    Dim columnCount As Long, rowsCount As Long
    Dim resultStr As String, codeStr As String
    columnCount = Zone.Columns.Count
    rowsCount = Zone.Rows.Count
    '参数判断
    If Code.Cells.Count <> 1 Then
        CollectMatchInfo2 = "#参数有误"
        Exit Function
    End If
    If columnCount < 2 Then
        CollectMatchInfo2 = "#参数有误"
        Exit Function
    End If
    '默认分隔符为 ;
    If Splitor = "" Then
        Splitor = ";"
    End If
    '函数功能
    codeStr = Trim(Code.Cells(1, 1))
    With Zone
        For i = 1 To rowsCount Step 1
            If .Cells(i, 1) = "" Then
                Exit For
            End If
            If Trim(.Cells(i, 1)) = codeStr Then
                '第一个匹配项,不添加分隔符
                If resultStr <> "" Then
                    resultStr = resultStr & Splitor & Chr(10)
                End If
                '循环添加后面的列
                For j = 2 To columnCount Step 1
                    If .Cells(i, j) <> "" Then
                        If j = 2 Then
                            resultStr = resultStr & .Cells(i, j)
                        Else
                            resultStr = resultStr & SplitorRow & .Cells(i, j)
                        End If
                        
                    End If
                Next
            End If
        Next
    End With
    CollectMatchInfo2 = resultStr
End Function

参数:

    1. Code :查询的内容
    2. Zone :查询的区域
    3. Splitor :行分隔符

 


'根据Code编码字符串,在Zone区域的第1列中查找匹配项,如果值等于Code 添加到返回内容里,返回所有的符合项。SplitorRow 查找到的行分隔符,查到数据列之间的分隔符为空格
Function CollectMatchInfo(Code As range, Zone As range, Splitor As String)
    CollectMatchInfo = CollectMatchInfo2(Code, Zone, Splitor, " ")
End Function

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值