Search code examples
excelvbaconcatenationuser-defined-functionstextjoin

How to concatenate multiple cells (only if cell is not blank) with delimiter?


I am trying to concatenate 6 cells with a delimiter of ", " in between each cell, but while ignoring blank cells. I used this question to help me: How to Concatenate multiple columns if not empty.

Problem:

I ran into an issue where the delimiter showed up at the end of the concatenated text. So I used LEFT and LEN to get rid of the extra character. Is there a way to fix this in VBA without using LEFT and LEN in a formula?

VBA Code:

Function Concat(ConcatArea As Range) As String
    For Each x In ConcatArea: xx = IIf(x = "", xx & "", xx & x & ", "): Next
    Concat = Left(xx, Len(xx) - 1)
End Function

Formula:

=LEFT(Concat(Temp[@[En00]:[En05]]),LEN(Concat(Temp[@[En00]:[En05]]))-1)

Solution:

I was able to use a different UDF with the help of @Andreas and Alun Rowe's resource. The UDF seems to emulate the TEXTJOIN function (which is only available in Office 365/2019):

Function IMPLODE(Rng As Range, Sep As String)
    Dim TEMP As String
    For Each Cell In Rng
        If Cell.Value = "" Then
        Else
            TEMP = TEMP & Cell.Value & Sep
        End If
    Next Cell
    TEMP = Left(TEMP, Len(TEMP) - Len(Sep))
    IMPLODE = TEMP
End Function

Solution

  • You can use the PHP equivalent implode function as a UDF.
    All credits to the original author here.

    Function IMPLODE(Rng As Range, Sep As String)
        Dim TEMP As String
        For Each Cell In Rng
            If Cell.Value = "" Then
            Else
                TEMP = TEMP & Cell.Value & Sep
            End If
        Next Cell
        TEMP = Left(TEMP, Len(TEMP) - Len(Sep))
        IMPLODE = TEMP
    End Function