Excel - 合并具有共同值的行并连接一列中的差异

lar*_*lad 6 excel merge vba concatenation excel-formula

我想合并具有共同值的行并将差异连接在一列中。

我认为最简单的方法就是举个例子。

输入:

Customer Name   |   NEW YORK    |   ALBANY 
Customer Name   |   NEW YORK    |   CLINTON    
Customer Name   |   NEW YORK    |   COLUMBIA
Customer Name   |   NEW YORK    |   DELAWARE
Customer Name   |   NEW YORK    |   DUTCHESS  
Customer Name   |   VERMONT     |   BENNINGTON  
Customer Name   |   VERMONT     |   CALEDONIA
Customer Name   |   VERMONT     |   CHITTENDEN
Customer Name   |   VERMONT     |   ESSEX
Customer Name   |   VERMONT     |   FRANKLIN
Run Code Online (Sandbox Code Playgroud)

期望的输出:

Customer Name   |   VERMONT     |   BENNINGTON,CALEDONIA,CHITTENDEN,ESSEX,FRANKLIN
Customer Name   |   NEW YORK    |   ALBANY,CLINTON,COLUMBIA,DELAWARE,DUTCHESS
Run Code Online (Sandbox Code Playgroud)

我确实看到了其他一些关于此的帖子,但我认为它们并不是我想要做的。

mj8*_*j82 2

如果|您指的是单独的单元格,那么以下宏(Excel 2007)应该可以解决问题(您的数据从单元格 A1 开始):

Application.ScreenUpdating = False

last_row = Cells(Rows.Count, 1).End(xlUp).Row

'first: make sure data is sorted
Sort.SortFields.Clear
Sort.SortFields.Add Key:=Columns("A:A"), SortOn:=xlSortOnValues
Sort.SortFields.Add Key:=Columns("B:B"), SortOn:=xlSortOnValues
Sort.SortFields.Add Key:=Columns("C:C"), SortOn:=xlSortOnValues

With Sort
    .SetRange Range("A1:C" & last_row)
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

'then: join text until key values in two neighboring row changes
myText = ""
myPos = 1

For i = 1 To last_row
    If Cells(i, 1).Value <> Cells(i + 1, 1).Value Or Cells(i, 2).Value <> Cells(i + 1, 2).Value Then
        Cells(myPos, 5).Value = Cells(i, 1).Value
        Cells(myPos, 6).Value = Cells(i, 2).Value

        myText = myText & Cells(i, 3).Value
        Cells(myPos, 7).Value = myText
        myText = ""
        myPos = myPos + 1
    Else
        myText = myText & Cells(i, 3).Value & ","
    End If
Next i

Application.ScreenUpdating = True
MsgBox "Done"
Run Code Online (Sandbox Code Playgroud)