如何在Excel中合并行而不丢失数据

时间:2019-02-07 18:16:24

标签: excel

警告:我是新手!!

我在excel中有一个数据集,该数据集的设置与下面的数据集相同,但具有70列和11,000多个行。

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       

我希望上面的样子:

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

请帮助!非常感谢您抽出宝贵的时间阅读这篇文章,

1 个答案:

答案 0 :(得分:0)

  • 将数据收集到一个变量数组中
  • 向后处理数组中的排序规则
  • 将数据转储回工作表
  • 根据第一列删除重复项。

代码:

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