将包含多行数据的列转换为包含多列的行,删除重复的参考编号



我有一个类似于下面的数据集:

示例数据

我想将数据转换为多列,其中删除了重复的 ID(第 1 列(,并将所有其他数据合并为跨列拆分的单行。

我已经从另一个线程尝试了以下代码:

在Excel中将包含多行数据的列转换为具有多列的行。

但是,这会导致第二列数据也合并到行中存在重复项的列之间。

例如,上表将显示为

当前结果

我需要修改代码,以便它只删除第 1 列中的重复数据,并将剩余的数据分布在列中。

我希望数据结束如下:

期望的结果

以下是我正在使用的代码:


Sub ConsolidateRows_SpreadAcross()
Dim lastRow As Long, i As Long, j As Long
Dim colMatch As Variant, colConcat As Variant
application.ScreenUpdating = False 'disable ScreenUpdating to avoid screen flashes
lastRow = range("A" & Rows.Count).End(xlUp).Row 'get last row
For i = lastRow To 2 Step -1
    If Cells(i, 2) = Cells(i - 1, 2) Then
        range(Cells(i, 3), Cells(i, Columns.Count).End(xlToLeft)).Copy Cells(i - 1, Columns.Count).End(xlToLeft).Offset(, 1)
        Rows(i).Delete
    Else
        If Cells(i, 1) = Cells(i - 1, 1) Then
            range(Cells(i, 2), Cells(i, Columns.Count).End(xlToLeft)).Copy _
                Cells(i - 1, Columns.Count).End(xlToLeft).Offset(, 1)
            Rows(i).Delete
        End If
    End If
Next
application.ScreenUpdating = True 'reenable ScreenUpdating
End Sub

任何协助将不胜感激。

在数据处于当前模式的情况下,您无需同时检查 A 列和 B 列。

Sub ConsolidateRows_SpreadAcross()
    Dim i As Long, j As Long
    Dim colMatch As Variant, colConcat As Variant
    Application.ScreenUpdating = False 'disable ScreenUpdating to avoid screen flashes
    With Worksheets("sheet15")
        For i = .Cells(.Rows.Count, "A").End(xlUp).Row To 2 Step -1
            If .Cells(i, 1) = Cells(i - 1, 1) Then
                .Range(.Cells(i, 3), .Cells(i, .Columns.Count).End(xlToLeft)).Copy _
                  Destination:=.Cells(i - 1, .Columns.Count).End(xlToLeft).Offset(0, 1)
                .Rows(i).Delete
            End If
        Next i
        .Cells(1, "C").Resize(1, .Cells(1, 1).CurrentRegion.Columns.Count - 2) = "data"
    End With
    Application.ScreenUpdating = True 'reenable ScreenUpdating
End Sub

最新更新