如何将两列合并为一列,并使用excel中的宏将每个条目合并为一个新行?

时间:2016-01-06 21:16:30

标签: r excel excel-vba vba

我在excel中有以下格式的数据:
| 4 | 5 |
| 8 | 3 |
| 6 | 2 |

我想要输出格式:
4
5
8
3
6
2
如何在excel中使用Macro来完成这项工作?或者可以使用R?

中的数据框来完成

4 个答案:

答案 0 :(得分:0)

对于 A 列和 B 列中的数据,请在另一个单元格中输入:

=OFFSET($A$1,ROUNDUP(ROWS($1:1)/2,0)-1,MOD(ROWS($1:1)-1,2))

并复制下来:

enter image description here

注:

任何矩形数据块都可以映射到一个列,其公式与此类似。

答案 1 :(得分:0)

如果您正在寻找宏,请参考以下快速VBA代码:

Sub MergeColumns()
    'Declare some indexing variables
    Dim a, b, c, x As Integer

    ' x is where we want to put the column of merged numbers
    x = 3

    ' b is the index for which column to pickup
    ' start this at 1
    ' c is the row we wan to pick up, start it at 2
    b = 1
    c = 2

    ' Next loop through all the numbers on the left side
    For a = 2 To 7
        ' first set our first cell to the correct value
        Cells(a, x) = Cells(c, b)

        ' now we change the indexes
        If b = 1 Then
            ' change to the next colum
            b = 2
        Else
            ' otherwise b = 2 and we need to move rows
            b = 1
            c = c + 1
        End If
    Next a
End Sub

enter image description here

答案 2 :(得分:0)

这是我的答案,希望能帮到任何人。

Sub rangeToColumn()
    Dim rng As Range
    Dim i 'index of cells
    Dim f

    Set rng = Range("A1:B3")
    i = 0

    For Each f In rng
        i = i + 1
        Cells(i, 3).Value = f.Value
        'Cells({a}, {b}).Value = {c}
        '
        'a = the row you want to put the value, using the index will put the value in separated rows
        'b = you can use the column you want, or used hardcoded as  I did.
        'c = storing each cell into the c var, you will be able to take the values or any other property.
    Next f
End Sub

答案 3 :(得分:0)

此公式使用Index。仅供将来参考,因为它类似于Gary的学生回答。但间接是不稳定的,因为如果有任何变化,它将重新计算。索引公式仅在其引用的数据发生更改时重新评估:

=INDEX($A$1:$B$3,QUOTIENT(ROW(1:1)-1,2)+1,MOD(ROW(1:1)+1,2)+1)

enter image description here