简体   繁体   中英

VBA: How to concatenate range of cells in a column with strings and generate it in another column?

I just can't work around this particular problem of mine where I have to concatenate all cells with data to a string, (eg " or ') in one column and then generate that concatenated result in another column.

Expected result:

Column A = ABCD
Column B = 'ABCD',

My Code

Option Explicit

Sub Concatenator ()

    Columns("B") = "'" & Range(Range("A1"), Range("A1").End(xlDown)) & "',"

End Sub

I would put the code in a FOR Loop :

Sub Concatenator()

Dim lastLng As Long

lastLng = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row

    For x = 1 To lastLng

    Cells(x, 2).Value = "'" & Cells(x, 1).Value & "',"

    Next x

End Sub

Alternatively, if you don't want to use a loop, you can use the code below to paste your formula in column B:

Sub Concatenator()

Dim lastLng As Long

lastLng = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row

    Range("B1:B" & lastLng).Formula = "=""'"" & A1 & "",'"""

End Sub

or you could use this

Sub Concatenator()   
    Range("A1", Cells(Rows.count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants, xlTextValues).Offset(, 1).Formula = "=concatenate(""'"",RC[-1],""'"")"    
End Sub

or this:

Sub Concatenator()
    With Range("A1", Cells(Rows.count, 1).End(xlUp))
        .Offset(, 1).Value = Application.Transpose(Split(Replace("'" & Join(Application.Transpose(.Value), "'|''") & "'", "'''", "''"), "|"))
    End With
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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