简体   繁体   中英

How do I transpose a column into a row in Excel

I have the following Excel worksheet:

   A
1 foo
2 bar
3 baz
4 bam

(In reality, the column is much, much longer making transponing by hand not an option). How can I transform this sheet into

   A   B   C   D
1 foo bar baz bam

I've tried the PivotTable function but am unable to get the output I want. I could also write a (php) script to read and transform the Excel, but I cannot imagine this is something that is not easily done in Excel. However, I have been unable to find the answer to this problem. Can you help?

There are two easy, non-programmatic ways:

  1. Copy the data and at the target, use Paste Special -> Transpose
  2. Apply the TRANSPOSE worksheet function: select the range of the transposed size (in your example 1 row x 4 columns and enter =TRANSPOSE(A1:A4) . You need to enter this as an array formula, ie press Ctrl - Shift - Enter

If for some reason you need to do this via code, this VBA code will do:

Sub CopyTransposed(rngSource As Range, rngTargetCell As Range)
    rngTargetCell.Resize(rngSource.Columns.Count, rngSource.Rows.Count).Value = _
        Application.WorksheetFunction.Transpose(rngSource)
End Sub

You can simply call it like this:

CopyTransposed [A1:A4], [C1] 

or to be more explicit

CopyTransposed Sheets("SourceSheet").Range("A1:A4"),Sheets("TargetSheet").Range("C1")

If you only need to transpose data, (ie no formats) try this

Sub zx()
    Dim rng As Range
    Dim dat As Variant

    With ActiveSheet ' can be any sheet
        Set rng = .[A1:A5] ' get refernce to your data, by any means
        dat = rng ' copy data to array
        rng.Clear ' clear old data

        ' paste transposed data
        .Range(rng.Cells(1, 1), Cells(rng.Row, rng.Rows.Count)) = Application.Transpose(dat)
    End With
End Sub

Ctrl+C to copy and paste using Paste Special. Click transpose on the dialog box.

This will paste it as values though....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM