简体   繁体   English

如何在Excel中将列转置为行

[英]How do I transpose a column into a row in Excel

I have the following Excel worksheet: 我有以下Excel工作表:

   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. 我也可以编写一个(php)脚本来读取和转换Excel,但是我无法想象这在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 应用TRANSPOSE工作表函数:选择转置大小的范围(在您的示例中为1行x 4列,然后输入=TRANSPOSE(A1:A4) 。您需要将此作为数组公式输入,即按Ctrl - Shift - Enter

If for some reason you need to do this via code, this VBA code will do: 如果出于某些原因需要通过代码执行此操作,则此VBA代码将执行以下操作:

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. Ctrl + C使用“选择性粘贴”进行复制和粘贴。 Click transpose on the dialog box. 单击对话框上的移调。

This will paste it as values though.... 但这会将其粘贴为值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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