转置 excel 中的日期以包含 header 行

Transpose date in excel to include header row

我有如下数据记录球员姓名和每轮踢球数。空白表示他们没有踢球 x 表示他们踢球但没有踢球。

Surname | First | Second | R1 | R2 | R3 | R4 | R5|
Smith   | Barry | John   | x  |    |    |    | 2 |
Jones   | Murry | Fred   | x  |  3 |  2 |  1 | 2 |
Wills   | Geoff | Mike   | x  |    |    |  x | x |

并且需要它显示如下:

Smith | Barry | John | R1 | x |
Smith | Barry | John | R5 | 2 |
Jones | Murry | Fred | R1 | x |
Jones | Murry | Fred | R2 | 3 |
Jones | Murry | Fred | R3 | 2 |
Jones | Murry | Fred | R4 | 1 |
Jones | Murry | Fred | R5 | 2 |
Wills | Geoff | Mike | R1 | x |
Wills | Geoff | Mike | R4 | x |
Wills | Geoff | Mike | R5 | x |

到目前为止我在 VBA

中有这段代码
Sub NewLayout()
    For i = 2 To Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
        For j = 0 To 4
        If Cells(i, 4 + j) <> vbNullString Then
            intCount = intCount + 1
            Cells(i, 1).Copy Destination:=Cells(intCount, 10)
            Cells(i, 2).Copy Destination:=Cells(intCount, 11)
            Cells(i, 3).Copy Destination:=Cells(intCount, 12)
            Cells(i, 4 + j).Copy Destination:=Cells(intCount, 13)
        End If
        Next j
    Next i
End Sub

在不返回 header 行即 R1、R2、R3 等的情况下,我得到了大部分我需要的东西。

要修改您的代码,您可以稍微更改最后的 copy 行,并添加一行以复制相关的 header 行

        Cells(i, 1).Copy Destination:=Cells(intcount, 10)
        Cells(i, 2).Copy Destination:=Cells(intcount, 11)
        Cells(i, 3).Copy Destination:=Cells(intcount, 12)
        Cells(1, 4 + j).Copy Destination:=Cells(intcount, 13)
        Cells(i, 4 + j).Copy Destination:=Cells(intcount, 14)

但我建议使用 Power Query,您所要做的就是

  • select前三列
  • 逆透视其他列

这可以从 UI 完成,但这里是 M-Code

M-Code

let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"Surname", "First", "Second"}, "Attribute", "Value")
in
    #"Unpivoted Other Columns"