Excel代码将多列表转换为具有重复模式的单列

时间:2018-12-13 14:38:36

标签: excel vba excel-vba

假设您在Excel中具有这样的列范围(表):

enter image description here

,需要将其转换为以下格式:

enter image description here

我已经搜索了here之类的VBA脚本,市场上有几种工具,但是无法使其在所需的输出中工作。

如何使用常规的Excel公式或VBA脚本执行此操作?

1 个答案:

答案 0 :(得分:2)

尝试:

Option Explicit

Sub test()

    Dim LC As Long, LR As Long, Number As Long, i As Long, j As Long, NR As Long
    Dim str As String

    'Everything included in "With Statement" refer to Sheet1
    With ThisWorkbook.Worksheets("Sheet1")

        'Find Last Column
        LC = .Cells(1, .Columns.Count).End(xlToLeft).Column

        'Find Las Row
        LR = .Cells(.Rows.Count, "A").End(xlUp).Row

        'Loop from column two to last column
        For i = 2 To LC

            'Number get the value of row 1 and column i
            Number = .Cells(1, i).Value

            'Loop from row two to last row of each i
            For j = 2 To LR

                'str get the value of row j in column 1
                str = .Cells(j, 1).Value

                    NR = .Cells(.Rows.Count, "A").End(xlUp).Row

                    .Cells(NR + 1, 1).Value = Number
                    .Cells(NR + 1, 2).Value = str
                    .Cells(NR + 1, 3).Value = .Cells(j, i).Value


            Next j

        Next i

    End With

End Sub

输出:

enter image description here