简体   繁体   中英

How to merge rows without losing data in excel

Warning: I am a newb!!!

I have a dataset in excel that is set up like the one below, but with 70ish columns and 11,000+ rows.

id          name    Birth   56    57    58
bob|1996    bob    1996     r       
bob|1996    bob    1996           r 
bob|1996    bob    1996                 r
bob|1997    bob    1997     s       

I want the above to look like:

id          name    Birth   56  57  58
bob|1996    bob     1996    r   r   r
bob|1997    bob     1997    s   

Please help! Thank you so much for taking the time to read this, btw.

  • Collect the data into a variant array
  • Process the collation within the array backwards
  • Dump the data back to the worksheet
  • Remove duplicates based on the first column.

Code:

Option Explicit

Sub Macro1()

    Dim i As Long, j As Long, arr As Variant

    With Worksheets("sheet10")

        'Collect the data into a variant array
        arr = .Range(.Cells(2, "A"), .Cells(.Rows.Count, "A").End(xlUp).Offset(0, 5)).Value2

        'Process the collation within the array backwards
        For i = UBound(arr, 1) To LBound(arr, 1) + 1 Step -1
            If arr(i, 1) = arr(i - 1, 1) Then
                For j = 4 To UBound(arr, 2)
                    arr(i - 1, j) = arr(i, j) & arr(i - 1, j)
                Next j
            End If
        Next i

        'Dump the data back to the worksheet
        .Cells(2, "A").Resize(UBound(arr, 1), UBound(arr, 2)) = arr

        'Remove duplicates based on the first column.
        With .Range(.Cells(1, "A"), .Cells(.Rows.Count, "A").End(xlUp).Offset(0, 5))
            .RemoveDuplicates Columns:=1, Header:=xlYes
        End With
    End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM