简体   繁体   English

Excel VBA将多列合并到一个单元格中

[英]Excel vba multiple columns into one cell

ROW1| 1 2 3
ROW2| A D G
ROW3| B E H
ROW4| C F I

I want output like this: 我想要这样的输出:

ROW1| 1
ROW2| A
ROW3| B
ROW4| C
ROW1| 2
ROW2| D
ROW3| E
ROW4| F
ROW1| 3
ROW2| G
ROW3| H
ROW4| I

Please help me 请帮我

Try this formula: 试试这个公式:

=IFERROR(INDEX($A$1:$C$4,MOD(ROW()-1,4)+1,INT((ROW()-1)/4)+1),"")

and drag/copy down as required. 并根据需要向下拖动/复制。

在此处输入图片说明

VBA Solution: VBA解决方案:

Sub RowsToColumn()
    Dim dict As Object
    Dim lastRow As Long, lastColumn As Long, cnt As Long
    Dim myRng As Range

    Set dict = CreateObject("Scripting.Dictionary")

    'get last row and column with data
    lastRow = Cells(Rows.Count, "A").End(xlUp).Row
    lastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
    'set your range here
    'Set myRng = Range("A1:C4")
    Set myRng = Range(Cells(1, 1), Cells(lastRow, lastColumn))

    cnt = 1
    'put cell value in dictionary
    For Each col In myRng.Columns
        For Each cel In col.Cells
            dict.Add cel.Value, cnt
            cnt = cnt + 1
        Next cel
    Next col
    'display values in dictionary
    Range("E1").Resize(dict.Count) = Application.Transpose(dict.keys)
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM