Excel VBA - Combine rows with duplicate values in one cell and merge values in other cell

前端 未结 6 1258
遇见更好的自我
遇见更好的自我 2020-11-27 23:28

I am trying to find duplicate values in one column and combine the values of a second column into one row. I also want to sum the values in a third column.

For examp

6条回答
  •  甜味超标
    2020-11-27 23:32

    Merging rows by summing the numbers from column D and building a string concatenation from column C with a semi-colon delimiter based upon duplicate values in columns A and B.

    Before¹:

            

    Code:

    Sub merge_A_to_D_data()
        Dim rw As Long, lr As Long, str As String, dbl As Double
        
        Application.ScreenUpdating = False
        With ActiveSheet.Cells(1, 1).CurrentRegion
            .Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _
                        Key2:=.Columns(2), Order2:=xlAscending, _
                        Orientation:=xlTopToBottom, Header:=xlYes
            lr = .Rows.Count
            For rw = .Rows.Count To 2 Step -1
                If .Cells(rw, 1).Value2 <> .Cells(rw - 1, 1).Value2 And _
                   .Cells(rw, 2).Value2 <> .Cells(rw - 1, 2).Value2 And rw < lr Then
                    .Cells(rw, 4) = Application.Sum(.Range(.Cells(rw, 4), .Cells(lr, 4)))
                    .Cells(rw, 3) = Join(Application.Transpose(.Range(.Cells(rw, 3), .Cells(lr, 3))), Chr(59))
                    .Cells(rw + 1, 1).Resize(lr - rw, 1).EntireRow.Delete
                    lr = rw - 1
                End If
            Next rw
        End With
        Application.ScreenUpdating = True
    End Sub
    

    After¹:

            

    ¹Some additional rows of data were added to the original posted data in order to demonstrate the sort.

提交回复
热议问题