将多列中的数据合并到一列中

时间:2015-05-20 01:21:22

标签: excel vba excel-vba

我有以下内容:
enter image description here


我正在使用@BigBobby's answer来实现这一目标:

Sub MoveData()
Range("H5:H99").ClearContents
START_ROW = 5
START_COL = 1
STEP_COL = 2
OUTPUT_ROW = 5
OUTPUT_COL = 8
Limit_Col = 9

Row = START_ROW
Col = START_COL
Out_Row = OUTPUT_ROW
While Col < Limit_Col
    While Cells(Row, Col).Value <> ""
        Cells(Out_Row, OUTPUT_COL).Value = Cells(Row, Col).Value
        Out_Row = Out_Row + 1
        Row = Row + 1
    Wend
    Row = START_ROW
    Col = Col + STEP_COL
Wend
End Sub


但是正如您所见,我希望获得列中空白单元格后出现的值。但是这段代码无法将这些单元格用黄色突出显示。
如何修改此代码以提取一个或多个空白单元格后可能出现的所有数据?

2 个答案:

答案 0 :(得分:2)

之前的答案很接近,但它也会复制所有空格。此代码应该满足您的需求:

Sub MoveData()

START_ROW = 5
START_COL = 1
STEP_COL = 2
OUTPUT_ROW = 5
OUTPUT_COL = 10

Row = START_ROW
Col = START_COL
Out_Row = OUTPUT_ROW
While Col < OUTPUT_COL
    While Row < ActiveSheet.UsedRange.Rows.Count
        If Cells(Row, Col).Value <> "" Then
            Cells(Out_Row, OUTPUT_COL).Value = Cells(Row, Col).Value
            Out_Row = Out_Row + 1
        End If
        Row = Row + 1
    Wend
    Row = START_ROW
    Col = Col + STEP_COL
Wend
End Sub

答案 1 :(得分:1)

调整此代码:

While Cells(Row, Col).Value <> ""
    Cells(Out_Row, OUTPUT_COL).Value = Cells(Row, Col).Value
    Out_Row = Out_Row + 1
    Row = Row + 1
Wend

有关:

Do until row > Cells(65536, Col).End(xlUp).Row
    Cells(Out_Row, OUTPUT_COL).Value = Cells(Row, Col).Value
    Out_Row = Out_Row + 1
    Row = Row + 1
Loop

这实质上是检查行是否已通过数据的最后一行,如果有,则移动到下一列。

修改

要不复制空白单元格,请使用:

    Do until row > Cells(65536, Col).End(xlUp).Row
        If Cells(Row, Col).Value <> "" then
            Cells(Out_Row, OUTPUT_COL).Value = Cells(Row, Col).Value
            Out_Row = Out_Row + 1
        End If
        Row = Row + 1
    Loop