逐行连接3列的值

时间:2014-07-07 00:18:36

标签: vba excel-vba excel

我正在尝试连接列(1,2,3)的值。结果应该在第(4)栏中。有n行应该进行连接。使用我创建的代码,每行都会处理,但每个结果单元格中的结果都会被添加和添加。我做错了什么?

Sub insertStatement()
Dim row As Integer
Dim lrow As Integer
Dim x As String
Dim cel As Range
Dim rng As Range

Sheets("INSERT").Select
row = 1
lrow = Cells(Rows.Count, 1).End(xlUp).row

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

    x = ""

    For Each cel In rng

        x = x & cel.Value

    Next

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

row = row + 1
Loop

End Sub

2 个答案:

答案 0 :(得分:3)

请尝试以下这个简单的目标。

Sub insertStatement()
    Const sFormulaR1C1 = "=CONCATENATE(RC[-3],RC[-2],RC[-1])"
    Dim lLastRow As Long

    With ThisWorkbook.Worksheets("INSERT")
        lLastRow = .Cells(Rows.Count, "A").End(xlUp).row
        .Range("D1:D" & lLastRow).FormulaR1C1 = sFormulaR1C1
    End With
End Sub

答案 1 :(得分:0)

在您设置范围的行...

Set rng = Range(.Cells(1, 1), .Cells(lrow, 3))

...您每次都使用第1行第1列作为起点。建议以下......

Set rng = Range(.Cells(row, 1), .Cells(lrow, 3))