如何"旋转" Excel中的数据(复杂转置)

时间:2015-02-02 21:40:53

标签: excel

说我有这些信息:

NAME  Class1 Class2 Class3
NAME2 Class2 Class3 Class4

我想把它变成:

NAME  Class1
NAME  Class2
NAME  Class3
NAME2  Class2
NAME2  Class3
NAME2  Class4

我会使用粘贴>转置,但我有550个名字,每个名称最多10个。所以我必须复制,插入10个空白行,粘贴>转置然后修剪空白行500次。

有更好的方法吗?

2 个答案:

答案 0 :(得分:1)

使用 Sheet1

中的数据

enter image description here

运行此宏:

Sub ReOrganize()
    Dim sh1 As Worksheet, sh2 As Worksheet
    Dim N As Long, i As Long, j As Long, k As Long
    Dim M As Long, v As String

    Set sh1 = Sheets("Sheet1")
    Set sh2 = Sheets("Sheet2")
    k = 1
    N = sh1.Cells(Rows.Count, "A").End(xlUp).Row

    For i = 1 To N
        v = Cells(i, 1).Value
        M = Cells(i, Columns.Count).End(xlToLeft).Column
        For j = 2 To M
            sh2.Cells(k, 1) = v
            sh2.Cells(k, 2) = sh1.Cells(i, j)
            k = k + 1
        Next j
    Next i
End Sub

将在 Sheet2

中生成此内容

enter image description here

答案 1 :(得分:1)

上面的答案看起来像我最后在https://superuser.com/questions/633124/how-do-i-split-one-row-into-multiple-rows-with-excel

找到的那个变种

我在该页面中使用的代码本身是:

Sub NewLayout()
    For i = 2 To Cells.Find("*", [A1], , , xlByRows, xlPrevious).Row
        For j = 0 To 2
        If Cells(i, 3 + j) <> vbNullString Then
            intCount = intCount + 1
            Cells(i, 1).Copy Destination:=Cells(intCount, 10)
            Cells(i, 2).Copy Destination:=Cells(intCount, 11)
            Cells(i, 3 + j).Copy Destination:=Cells(intCount, 12)
        End If
        Next j
    Next i
End Sub

而不是像上面的答案那样粘贴到新的工作表中,而是粘贴到同一张纸的第10-12列。