在Excel中将具有多行数据的列转换为具有多列的行.

问题描述:

我将数据组织在具有多行的cloumns中,我需要将其转换为具有多列的行以进行数据分析.例如,

I have data organised in cloumns with multiple rows which I need to convert to rows with multiple columns for data analysis. For example,

    ID  Date of entry   Location    Data1   Data2
    1   20101030        1           a       b
    1   20101030        2           c       d
    1   20101125        1           w       v
    1   20101125        2           e       d
    1   20110314        1           we      r
    1   20110314        2           f       f
    2   20091024        1           ewr     rte
    2   20091024        2           gr      ert
    3   20061128        1           jy      bf
    3   20061128        2           u       df
    3   20110517        1           rd      fd
    3   20110517        2           sg      sd

采用这种格式,每个ID行包含多列数据(下面仅显示头行)

into this format with each ID row with multiple columns of data (only head row shown below)

ID  entry_1 Dateofentry location_1  data1   data2   location_2  data1   data2   entry_2 Dateofentry location_1  data1   data2   location_2  data1   data2   entry_3 Dateofentry location_1  data1   data2   location_2  data1   data2

任何人都可以协助吗?

谢谢! GT

您必须自己添加标头,但是这段代码应该可以满足您的要求:

You'll have to add the headers yourself, but this code should do what you need:

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