用于将数据从行转换为列的 Excel VBA 代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37545372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:26:30  来源:igfitidea点击:

Excel VBA code to transpose data from rows to columns

excelvbaexcel-vba

提问by Siraj

I have data in column A with 50000 rows of data. I need to transpose every 6 rows of data to 6 columns. For example data from A1:A6 must be transposed to B1:G1. Again data from A7:A14 must be transposed to B2:G2. I appreciate if anyone can provide VBA code for this.

我在 A 列中有 50000 行数据的数据。我需要将每 6 行数据转置为 6 列。例如,来自 A1:A6 的数据必须转置为 B1:G1。来自 A7:A14 的数据必须再次转换为 B2:G2。如果有人可以为此提供 VBA 代码,我将不胜感激。

Data I have in column A is as shown below:

我在A列中的数据如下所示:

Col A
1
2
3
4
5
6
7
8
9
10
11
12

The transpose data must be as shown below in col B to col G:

转置数据必须如下所示在 col B 到 col G 中:

Columns  B   C   D   E   F   G
         1   2   3   4   5   6
         7   8   9   10  11  12

回答by Mrig

Try this:

尝试这个:

Sub TransposeRows()
    Dim rng As Range
    Dim i As Long

    Set rng = Range("A1")
    While rng.Value <> ""
        i = i + 1
        rng.Resize(6).Copy
        Range("B" & i).PasteSpecial Transpose:=True
        Set rng = rng.Offset(6)            
    Wend
    Application.CutCopyMode = False
End Sub

Got this from here.

这里得到这个。

回答by Gary's Student

You do not need a macro for this. In B1enter:

为此,您不需要宏。在B1 中输入:

=OFFSET($A,COLUMNS($A:A)-1+(ROWS(:1)-1)*6,0)

Then copy both across and down:

然后上下复制:

enter image description here

在此处输入图片说明

回答by Vasily

additional variant from my side:

我这边的其他变体:

Sub TransposeRows2()
    Dim i&, z&, x&
    i = Cells(Rows.Count, "A").End(xlUp).Row
    z = 1: x = 1
    While z <= i
        Range("B" & x).Resize(, 6) = _
            WorksheetFunction.Transpose(Range("A" & z).Resize(6))
        z = z + 6: x = x + 1
    Wend
End Sub

tested:

测试:

enter image description here

在此处输入图片说明

回答by Miguel ?ngelo Rodrigues

In Portuguese Excel, "Gary's Student"'s formula, for 4 columns instead of 6, becomes:

在葡萄牙语 Excel 中,“Gary's Student”的公式(4 列而不是 6 列)变为:

=DESLOCAMENTO($A;COLS($A:A)-1+(LINS(:1)-1)*4;0)