Excel – 合并具有公共值的行并在一列中连接差异

我想将行与常用值合并,并在一列中连接差异.

我认为最容易做的就是给你一个例子.

输入:

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

期望的输出:

Customer Name   |   VERMONT     |   BENNINGTON,CALEDONIA,CHITTENDEN,ESSEX,FRANKLIN
Customer Name   |   NEW YORK    |   ALBANY,CLINTON,COLUMBIA,DELAWARE,DUTCHESS

我确实看到了其他一些帖子,但我不认为它们正是我试图做的.

最佳答案 如果通过|你的意思是separete单元格,然后跟随宏(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"
点赞