[英]Excel - Mix multiple columns into one column
我有兩列
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
我嘗試了很多例子,但沒有一個奏效。我是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
為此,您實際上並不需要 VBA。 您可以使用一個公式:
=IFERROR(INDEX($A$1:$B$3,INT((ROWS($1:1)-1)/2)+1,MOD(ROWS($1:1)-1,2)+1),"")
將 array_range 調整為您的數據的真實值,然后向下填充。
您可以使用此公式並將其向下拖動。
=OFFSET($A$1,(EVEN(ROW(A6))-2)/2,MOD(ROW(A6)-1,2))
其中 A1 是您的第一個單元格。 在上面的示例位置“A”
你可以用 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
雖然 Ros 的回答非常優雅,但從某種意義上說它不使用 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.