我具有以下数据,其中记录了球员的姓名和每轮踢的进球数。空白表示他们没有打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
在不返回标题行即R1,R2,R3等的情况下,得到了我所需的大部分东西。
要修改代码,您可以稍微更改最后的copy
行,并添加一行以复制相关的标题行
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
,您要做的只是
可以通过用户界面完成,但这里是M代码
M代码
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(Source, {"Surname", "First", "Second"}, "Attribute", "Value")
in
#"Unpivoted Other Columns"