如何将数据集转换为特定顺序?

时间:2019-01-18 11:11:20

标签: excel vba transpose excel-2016

我正在使用Excel 2016,并且我有一个包含492行且没有标题的数据集。数据从单元格A1开始。

数据集的摘录如下:

extract

我想转置此数据集,使其变为以下格式:

expected output

我是VBA的新手,我很难找到正确的解决方案。我尝试将移调记录为Macro(逐步操作)并查看了VBA代码,但仍然无法将它们组合在一起。

1 个答案:

答案 0 :(得分:1)

尝试使用此代码,但在调整顶部的两个常量以匹配工作表上的事实之前,请先进行尝试。执行代码后,带有数据的工作表必须处于活动状态。

Sub TransposeData()

    Const FirstDataRow As Long = 2              ' presuming row 1 has headers
    Const YearColumn As String = "A"            ' change as applicable

    Dim Rng As Range
    Dim Arr As Variant, Pos As Variant
    Dim Rl As Long, Cl As Long
    Dim R As Long, C As Long
    Dim i As Long

    With ActiveSheet
        Cl = .UsedRange.Columns.Count - .UsedRange.Column + 1
        Rl = .Cells(.Rows.Count, Columns(YearColumn).Column).End(xlUp).Row
        Set Rng = Range(.Cells(FirstDataRow, YearColumn), .Cells(Rl, Cl))
    End With
    Arr = Rng.Value
    ReDim Pos(1 To (UBound(Arr) * UBound(Arr, 2)), 1 To 2)

    For R = 1 To UBound(Arr)
        For C = 2 To UBound(Arr, 2)
            i = i + 1
            Pos(i, 1) = Arr(R, 1)
            Pos(i, 2) = Arr(R, C)
        Next C
    Next R

    R = Rl + 5                                  ' write 5 rows below existing data
    Set Rng = ActiveSheet.Cells(R, YearColumn).Resize(i, 2)
    Rng.Value = Pos
End Sub