如何使用VBA重塑excel中的数据

我有一个数据集看起来像这样:

ID | Date1| Thing1| Date2| Thing2| Date3| Thing3| Date4| Thing4| 1 | a | xx | b | xx | c | xx | d | xx | 2 | e | xx | f | xx | g | xx | h | xx | 

我想改变这样一个长桌:

 ID | Date| Thing| 1 | a | xx | 1 | b | xx | 1 | c | xx | 1 | d | xx | 2 | e | xx | 2 | f | xx | 2 | g | xx | 2 | h | xx | 

我知道如何在R中做到这一点,但是在excel中我真的很困惑。

任何人都可以帮我设置一些VBA代码?

提前致谢

这里是我的一个变种

 Sub test() Dim Key, Dic As Object, cl As Range, Data As Range, i&, n& Set Dic = CreateObject("Scripting.Dictionary") Dic.CompareMode = vbTextCompare i = Cells(Rows.Count, "A").End(xlUp).Row n = 1 Set Data = Range("B2:B" & i & "," & "D2:D" & i & "," & "F2:F" & i & "," & "H2:H" & i) Dic.Add "|ID", "Date|Thing" For Each cl In Data If Cells(cl.Row, "A") <> "" Then Dic.Add n & "|" & Cells(cl.Row, "A"), cl.Text & "|" & cl.Offset(, 1).Text n = n + 1 End If Next cl n = 1 For Each Key In Dic Cells(n, "K") = Split(Key, "|")(1) Cells(n, "L") = Split(Dic(Key), "|")(0) Cells(n, "M") = Split(Dic(Key), "|")(1) n = n + 1 Next Key End Sub 

产量

在这里输入图像说明

有3个问题与你非常相似

获取第一列值和其他列值的所有组合

从列中将类别提取到具有新类别的重复行中

https://superuser.com/questions/683413/transform-horizo​​ntal-table-layout-to-vertical-table

我会适应https://superuser.com/a/683439/245595你的情况,这很容易&#x3002; 一些您需要的轻微更改:

  1. 根据需要扩展rng_all

  2. 而不是使用icolncols等,并横扫每个ID的列,你不得不使用ncasesncases等,并横扫案件:

    ncases = ( WorksheetFunction.CountA(rng_curr) - 1 ) / 2
    For icase = 1 To ncases

  3. 更改循环内的slighlty代码。

  4. 添加用于复制每个案例的第三列的代码。

如果非VBA可以,可以使用。