如何使用定界符连接多个单元格(仅当单元格不为空白时)?

时间:2019-08-19 20:33:22

标签: excel vba concatenation user-defined-functions textjoin

我试图在6个单元格之间用分隔符“,”连接起来,但是忽略了空白单元格。我用这个问题来帮助我:How to Concatenate multiple columns if not empty

问题:

我遇到了一个问题,其中分隔符出现在串联文本的末尾。因此,我使用LEFT和LEN摆脱了多余的字符。有没有一种方法可以在VBA中解决此问题,而无需在公式中使用LEFT和LEN?

VBA代码:

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

公式:

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

解决方案:

借助@AndreasAlun Rowe's resource,我可以使用其他UDF。 UDF似乎模仿TEXTJOIN函数(仅在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

1 个答案:

答案 0 :(得分:0)

您可以将PHP等价的爆破功能用作UDF。
所有功劳归原始作者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