concatenate unknown number of column and rows [duplicate]

独自空忆成欢 提交于 2020-01-11 11:29:29

问题


I am trying something since a couple of days and I am really lost about it. Could someone help me about it please.

I would like to concatenate columns in Excel from the first column to the last non-empty column and add a comma between each column.

Following that, I would like to apply the loop from the first line to the last non-empty line.

I succeed to do it with a known number of column (I add the code after) but not when the number of column is unknown.

Range("H2").Select
ActiveCell.FormulaR1C1 = _
    "=CONCATENATE(RC[-7],"","",RC[-6],"","",RC[-5],"","",RC[-4],"","",RC[-3],"","",RC[-2])"
Range("H2").Select
Selection.AutoFill Destination:=Range("H2:H" & Range("A2").End(xlDown).Row), Type:=xlFillDefault

回答1:


Here's TEXTJOIN for versions that don't have it (Excel 2013 and prior):

Option Explicit
Function TEXTJOIN(delimiter As String, ignore_empty As String, ParamArray textn() As Variant) As String
    Dim i As Long
    For i = LBound(textn) To UBound(textn) - 1
        If Len(textn(i)) = 0 Then
            If Not ignore_empty = True Then
                TEXTJOIN = TEXTJOIN & textn(i) & delimiter
            End If
        Else
            TEXTJOIN = TEXTJOIN & textn(i) & delimiter
        End If
    Next
    TEXTJOIN = TEXTJOIN & textn(UBound(textn))
End Function

(Source)


Example:

If you wanted to concatenate every populated cell in Column A, using comma as delimiter, you'd use:

=TEXTJOIN(",",TRUE,A:A)


来源:https://stackoverflow.com/questions/50741018/concatenate-unknown-number-of-column-and-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!