2016-04-23 77 views
1

我有兩列Excel中 - 混合多個列合併到一列

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

我想這樣

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

我試過很多例子混合列,但他們都不worked.I是新手到vba。請幫助 我從另一個堆棧溢出示例下面嘗試了一個,但它只會添加到最後一個單元格關閉列。我不知道如何更改它。

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 

回答

4

你並不真的需要VBA。你可以使用一個公式:

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

調整array_range到你的數據真正是什麼,並填寫。

+0

謝謝這是工作。我可以在哪裏添加陣列範圍?。給您帶來不便。 –

+0

@wondersofnature'array'是'Index'函數的第一個參數。 「範圍」是指構成該範圍的單元格。有關範圍的討論,以及如何引用它們,請參閱** Range **的幫助。有關「索引」功能的討論,請參閱該功能的幫助。 –

1

你可以用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 
+1

如果不是直接填充單元格,而是聲明另一個數組(例如'Dim Arr3(1 to Ubound(Arr1,1)* 2,1 to 1)',則填充該數組,然後寫入數組(例如'Cells(1,「C」)。resize(ubound(Arr3,1))。value = arr3') –

+1

您可以將for循環合併爲2對於i = 2到UBound(Arr1,1)* 2步驟2',然後使用'.Cells(i-1,「A」)= Arr1(i/2,1)'和'.Cells(i,「A 「)= Arr2(i/2,1)' 或者你可以通過使用'.Cells(i * 2,」A「)和'.Cells(j * 2,」A「)來消除額外的計數器' – OSUZorba

+0

感謝您的建議 – manu

1

雖然羅斯的回答也相當考究,在這個意義上它不使用VBA,我離開使用VBA的答案,因爲這個問題是關於VBA。

以下代碼假定第1列和第2列是工作表的列A和B,並且ActiveCell是單元格A1。輸出在列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 
2

您可以使用此公式並將其向下拖動。

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

其中A1是你的第一個細胞。在上面的例子中「A」的位置