简体   繁体   中英

Excel - Mix multiple columns into one column

I have two columns

          Column 1 Column 2
row 1:       A        1
row 2:       B        2
row 3:       C        3

I want to mix column like this

          Column 1 
row 1:       A      
row 2:       1        
row 3:       B
row 4:       2
row 5:       C
row 6:       3

I tried many examples but none of them worked.I am newbie to vba . Please help I tried one below from another stack overflow example.but it will add only on last cell off column.I don't know how to change it.

Sub CombineColumns()
Dim rng As Range
Dim iCol As Integer
Dim lastCell As Integer

Set rng = ActiveCell.CurrentRegion
lastCell = rng.Columns(1).Rows.Count + 1

For iCol = 2 To rng.Columns.Count
    Range(Cells(1, iCol), Cells(rng.Columns(iCol).Rows.Count, iCol)).Cut
    ActiveSheet.Paste Destination:=Cells(lastCell, 1)
    lastCell = lastCell + rng.Columns(iCol).Rows.Count
Next iCol
End Sub

You don't really need VBA for this. You can use a formula:

=IFERROR(INDEX($A$1:$B$3,INT((ROWS($1:1)-1)/2)+1,MOD(ROWS($1:1)-1,2)+1),"")

Adjust the array_range to what your data really is, and fill down.

You can use this formula and drag it down.

=OFFSET($A$1,(EVEN(ROW(A6))-2)/2,MOD(ROW(A6)-1,2))

where A1 is your 1st cell. In the above example location of "A"

You can do it like so with VBA:

Option Explicit
Sub Mix()

Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
Dim i As Long, j As Long, Rng1 As Range, Rng2 As Range
Dim Lastrow As Long, Arr1() As Variant, Arr2() As Variant
Dim n As Long, a As Long

With ws

Lastrow = .Range("A" & Rows.Count).End(xlUp).Row
Set Rng1 = .Range(.Cells(1, "A"), .Cells(Lastrow, "A"))
Set Rng2 = .Range(.Cells(1, "B"), .Cells(Lastrow, "B"))

Arr1 = Rng1.Value2
Arr2 = Rng2.Value2

n = 1
For i = LBound(Arr1, 1) To UBound(Arr1, 1)
    .Cells(n, "A") = Arr1(i, 1)
    n = n + 2
Next i

a = 2
For j = LBound(Arr2, 1) To UBound(Arr2, 1)
    .Cells(a, "A") = Arr2(j, 1)
a = a + 2
Next j

End With

End Sub

While Ros answer is quite elegant, in the sense it does not use VBA, I leave the answer using VBA, since the question is regarding VBA.

The following code assumes column 1 and 2 are columns A and B of the worksheet and that the ActiveCell is Cell A1. The output is on column C.

Sub CombineColumns()
    Dim rng As Range
    Dim iCell As Integer

    Set rng = ActiveCell.CurrentRegion

    Dim iCell As Integer
    For iCell = 1 To rng.Cells.Count
        Range("C1").Offset(iCell - 1, 0) = rng.Item(iCell)
    Next iCell

End Sub

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