Excel - 将多个列混合到一列中

时间:2016-04-23 12:28:49

标签: excel vba excel-vba

我有两列

<div id="test">
  <input type="text" id="txtBox" onchange="char_convert(this);" />
</div>

我想像这样混合列

          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

4 个答案:

答案 0 :(得分:4)

你真的不需要VBA。您可以使用公式:

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

将array_range调整为您的数据,并填写。

答案 1 :(得分:2)

您可以使用此公式并将其向下拖动。

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

其中A1是你的第一个细胞。在上面的示例位置“A”

答案 2 :(得分: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

答案 3 :(得分:1)

虽然Ros的答案非常优雅,但从某种意义上说它不使用VBA,我使用VBA留下答案,因为问题是关于VBA。

以下代码假定第1列和第2列是工作表的A列和B列,而ActiveCell是Cell 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