Excel VBA
Excel按条件合并多个单元格的内容到指定单元格内
2017-10-16 16:25:30

在excel表格中,我们有时需要合并多个单元格的内容到指定的单元格中。

如图,比方说需要把每个人购买的水果合并到一个单元格内。每个水果用“,”隔开。

Excel中有自带函数CONCATENATE,它可以将多个文本字符串合并成一个文本字符串,但它不能指定条件合并某些单元格的内容到一个单元格,这时CONCATENATE函数无法实现。

自定义函数:

Function CONCATENATEIF(rng1 As Range, rng2 As Range, criteria As String, separator As String) As String     Dim arr()     Dim rCell As Range     Dim i As Integer, j As Integer     On Error Resume Next     j = WorksheetFunction.CountIf(rng2, criteria)     If j > 0 Then         ReDim arr(0 To j - 1)         For Each rCell In rng2             If WorksheetFunction.CountIf(rCell, criteria) Then                 arr(i) = rng1.Item(1).Offset(rCell.Row - rng2.Row, rCell.Column - rng2.Column).Value                 i = i + 1             End If         Next         For i = 0 To j - 1             CONCATENATEIF = CONCATENATEIF & arr(i) & IIf(i <> j - 1, separator, "")         Next     End If End Function

此自定义函数CONCATENATEIF有四个参数,分别是①需要连接单元格内容的区域(通常为单行或单列)、②条件区域,③条件,④分隔符。

注意:函数可以使用“*“,”?”等通配符.

在单元格中录入函数,填写相关的参数即可:=CONCATENATEIF(C2:C14,B2:B14,F2,",")

效果如下图: