【问题标题】:How to use VBA to reshape data in excel如何使用 VBA 重塑 Excel 中的数据
【发布时间】:2015-05-28 05:17:13
【问题描述】:

我有一个数据集如下所示:

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 代码?

提前致谢

【问题讨论】:

  • 使用宏记录器开始。它将记录您手动执行的操作并将其转换为您可以在 VBA 编辑器中查看的代码。简单的复制和粘贴就可以了。
  • 如果ID 列也被重复,您可以使用idea here 采用公式方法。

标签: vba excel


【解决方案1】:

这是我这边的变种之一

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

输出

【讨论】:

  • 谢谢,我会试试这样的
【解决方案2】:

有 3 个问题与你的问题非常相似

Get all combinations of the first column's value and other column's value

Extract categories from columns into duplicated rows with new category

https://superuser.com/questions/683413/transform-horizontal-table-layout-to-vertical-table

我会根据您的情况调整答案https://superuser.com/a/683439/245595,这很容易。您需要的一些细微改动:

  1. 根据需要扩展rng_all

  2. 您必须使用icasencases 等,而不是使用icolncols 等并扫过每个ID 的列,并扫过案例:

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

  3. 在循环内更改少量代码。

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

如果非VBA没问题,可以使用this

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 2018-07-03
    • 2023-03-16
    • 2017-07-20
    • 2014-01-07
    • 2021-06-25
    • 2016-01-22
    相关资源
    最近更新 更多