如何在Excel中将多个单元格在行中转置为列

时间:2016-10-11 15:33:47

标签: excel excel-vba transpose vba

我的数据看起来像:

name    field1  field2  field3
John    abc     dcf     fdd
Sue     ddf     
Beth    fds     rtfds   

我希望它看起来像这样:

abc     John
dcf     John
fdd     John
ddf     Sue
fds     Beth
rtfds   Beth

请注意,行中包含可变数量的fieldx列...我尝试使用VBA script from MrExcel并获取"应用程序定义或对象定义错误。"

有没有办法只使用excel公式来做到这一点?我可以发布VBA脚本,但如果有更好的公式解决方案。

1 个答案:

答案 0 :(得分:0)

假设您的数据在A1的单元Sheet1中开始,并且您希望转置为Sheet2,则以下内容将起作用:

Sub test()

    Dim s1 As Worksheet
    Dim s2 As Worksheet
    Dim lCol As Long
    Dim i As Long
    Dim lRow As Long

    Set s1 = Sheets("Sheet1")
    Set s2 = Sheets("Sheet2")

    With s1

        lRow = .Cells(.Rows.Count, 1).End(xlUp).Row

        For i = 2 To lRow

            lCol = .Cells(i, .Columns.Count).End(xlToLeft).Column

            .Range(.Cells(i, 2), .Cells(i, lCol)).Copy

            s2.Cells(1, i - 1).PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
                False, Transpose:=True

        Next i

    End With

End Sub