逐行连接所有列

时间:2018-08-17 21:40:46

标签: excel vba excel-vba excel-formula

我正在尝试将所有列逐行连接。这段代码可以正常工作,但是一直循环播放,直到excel关闭。我如何确保它只循环等于所使用的行总数的次数?

这是我当前正在使用的代码:

Sub Combine_row_by_row()

Dim LastRow As Long

Dim x As String
Dim rng As Range
Dim cel As Range
Dim ColMax As Integer
Dim i As Long

LastRow = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).row
ColMax = Cells(1, Columns.Count).End(xlToLeft).Column

    row = 1
Do While Cells(row, "A").value < LastRow
    With Worksheets("Formula2")
        Set rng = Range(.Cells(row, 1), .Cells(row, ColMax))
    End With

    x = ""

    For Each cel In rng

        x = x & cel.value

    Next

    Sheets("Formula2").Cells(row, 1).value = x

row = row + 1
Loop

End Sub

1 个答案:

答案 0 :(得分:0)

Cells(row,“ A”)。Value返回单元格中的内容。除非该列包含行号列表,否则这些值可能永远不会超出LastRow变量的值。您可能需要Cells(row,“ A”)。Row