以动态方式逐行连接列值

时间:2014-07-03 18:07:16

标签: vba excel-vba excel

我的代码连接表“Data”的第一行的列的值,并将结果写入表“Insert”单元格A1。

错误是下一行的串联结果在表“Insert”A1中的第一个结果的末尾添加,依此类推。结果也应该逐行写在A列表中“插入”。

我的代码出了什么问题?

Sub InsertStatementRow()
Dim x As String
Dim rng As Range
Dim cel As Range
Dim ColMax As Integer
Dim i As Long

    Sheets("Data").Select

        ColMax = Cells(1, Columns.Count).End(xlToLeft).Column

    row = 1
    Do While Cells(row, "A").Value <> ""

        With Worksheets("Data")
        i = 1
        Set rng = Range(.Cells(i, 1), .Cells(i, ColMax))
        End With

        For Each cel In rng

            x = x & cel.Value

        Next

        Sheets("Insert").Cells(i, 1).Value = x

    row = row + 1
    Loop

End Sub

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

你设置

i=1

Set rng = Range(.Cells(i, 1), .Cells(i, ColMax))

但你好像在使用变量row。请删除/评论专栏i=1并更改Set rng

Set rng = Range(.Cells(row, 1), .Cells(row, ColMax))

希望它能解决你的问题。

答案 1 :(得分:0)

每次Do While循环开始时,我都被设置为“1”,因此rng变量将始终引用数据工作表的第1行。它还复制到插入工作表上的第1行。将i更改为行,它应该可以工作:

Do While Cells(row, "A").Value <> ""
    With Worksheets("Data")
        Set rng = Range(.Cells(row, 1), .Cells(row, ColMax))
    End With

    x = ""

    For Each cel In rng

        x = x & cel.Value

    Next

    Sheets("Insert").Cells(row, 1).Value = x

row = row + 1
Loop