我有一組複雜的數據,需要在 Excel 中重新排列。
桌子看起來像這樣
+----+--------+--------+--------+--------+
| ID | Text A | Text B | Text C | Text D |
+----+--------+--------+--------+--------+
| 1 | xx | | yy | zz |
+----+--------+--------+--------+--------+
| 2 | | aa | bb | |
+----+--------+--------+--------+--------+
| 3 | cc | | | dd |
+----+--------+--------+--------+--------+
我需要輸出的結果本質上是轉置和合併的組合。但我不知道如何在 Excel 中解決這個問題。
+----+------+
| ID | Text |
+----+------+
| 1 | xx |
+----+------+
| 1 | yy |
+----+------+
| 1 | zz |
+----+------+
| 2 | aa |
+----+------+
| 2 | bb |
+----+------+
| 3 | cc |
+----+------+
| 3 | dd |
+----+------+
答案1
這假設原始資料位於表1輸出將被放置在表2。
運行這個短宏:
Sub ReOrganizer()
Dim N As Long, nCols As Long
Dim i As Long, j As Long, k As Long
Dim s1 As Worksheet, s2 As Worksheet
Set s1 = Sheets("Sheet1")
Set s2 = Sheets("Sheet2")
N = s1.Cells(Rows.Count, 1).End(xlUp).Row
nCols = 5
k = 2
For i = 2 To N
Item = s1.Cells(i, 1)
For j = 2 To nCols
If s1.Cells(i, j) <> "" Then
s2.Cells(k, 1) = Item
s2.Cells(k, 2) = s1.Cells(i, j)
k = k + 1
End If
Next j
Next i
End Sub
將採用這樣的數據表1:
並在中生產這個表2: