Pagebanner

ThreeWave String Concatenation

This page describes a VBA Function that you can use to concatenate string values in an array formula.
ShortFadeBar

Introduction To Concatenation

The term concatenate refers to the operation of combining two or more strings into a single string. For example, the concatenation of abc and def is abcdef. Excel provides a function named CONCATENATE that will concatenate a series of strings. This function suffers from several very significant deficiencies, making is an essentailly useless function. First, you must supply each text value to CONCATENATE; you cannot pass a range to CONCATENATE and have it concatenate all the elements in the range. A second definciency is that CONCATENATE provides no way to automatically include a separater character between each of the concatenated strings. Finally, CONCATENATE cannot be used in array formulas (see Array Formulas for more information about array formulas) to build a string based on conditional tests.

Given these deficiencies of the CONCATENATE function, you can just as well use the concatenation operator &. There is no advantage to using CONCATENATE.

SectionBreak

The StringConcat Function

In order to overcome these deficiencies of the CONCATENATE function, it is necessary to build our own function written in VBA that will address the problems of CONCATENATE. The rest of this page describes such a function named StringConcat. This function overcomes all of the deficiencies of CONCATENATE. It can be used to concatenate individual string values, the values one or more worksheet ranges, literal arrays, and the results of an array formula operation. The function declaration of StringConcat is as follows:

Function StringConcat(Sep As String, SkipEmpty As Boolean, ParamArray Args()) As String
The Sep parameter is a character or characters that separate the strings being concatenated. This may be 0 or more characters. The Sep parameter is required. If you do not want any separators in the result string, use an empty string for the value of Sep. The Sep value appears between each string element being concatenated, but does not appear at either the beginning or end of the result string. The SkipEmpty parameter indicates whether empty element in the Args array are to be skipped. If this value is False, there may be consecutive Sep characters indicating empty values. For example, =StringConcat(A1:A5) might return 1,2,,4,5 if cell A3 is empty. If this parameter is True, empty elements will be skipped and there will be no consecutive delimiters. It is important to distinguish between an empty value and a string value that contains a space character, Chr(32). The SkipEmpty parameter, if True, will cause empty values to be ignored, but text that contains only a space character will be included. The ParamArray Args array contains the strings elements to be concatenated. Each element in the Args array can be one of the following.

  • A string within quotes or a number. For exampe, "A" or 123.
  • A single cell reference. For example, A10.
  • A range of cells. For example, A1:B10.
  • A literal array constant. For example, {1,2,"A","B","C"}.

The following are a few examples of the StringConcat function.

Concatenating literal text:
=StringConcat("|",TRUE,"A","B","C")
returns A|B|C

Concatenating text in a range of cells:
=StringConcat("|",TRUE,B1:B5)
returns the values from B1:B5, each separated by a | character.

Concatenation In An Array Formula
=StringConcat("|",TRUE,IF(B30:B39>4,C30:C39,""))
returns the values from cells C30:C39, separated by a | character where the corresponding value in the range B30:B39 is greater than 4.

download You can download the file with all the example code on this page.

SectionBreak

The StringConcat Code

SectionBreak

Function StringConcat(Sep As String, SkipEmpty As Boolean, ParamArray Args()) As String
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' StringConcat
' Author: Chip Pearson, chip@cpearson.com
'               http://www.cpearson.com/Excel/StringConcatenation.aspx
' Date: 19-Dec-2004, Revised 14-June-2009
'
' This function concatenates all the elements in the Args array,
' delimited by the Sep character, into a single string. This function
' can be used in an array formula.
' Parameters:
'   Sep         the character, such as a comma, that should delimit
'               all of the values in the Args param array.
'   SkipEmpty   if True, blank values will be ignored, which is prevent
'               multiple delimiter separating empty strings. If this value is
'               True, there will be no consecutive delimiters. If the value is
'               false, there might be consectutive delmiters indicating empty
'               values.
'   Args        a list of parameters to concatenate. Each element in Args
'               can be any of the following:
'                   String
'                   Number
'                   Single Cell reference
'                   Multiple Cell reference
'                   Single Dimensional array
'                   2 Dimensional Array
'                   Array constants.
'               For example, the following formula mixes the various
'               input types:
'                   =StringConcat(",",TRUE,1,2,3,"abc","def",A1:A10,B1:C10,{11,22,33,44,55})

'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Dim S As String
Dim N As Long
Dim M As Long
Dim R As Range
Dim NumDims As Long
Dim LB As Long
Dim IsArrayAlloc As Boolean
Dim RN As Long
Dim CN As Long

'''''''''''''''''''''''''''''''''''''''''''
' If no parameters were passed in, return
' vbNullString.
'''''''''''''''''''''''''''''''''''''''''''
If UBound(Args) - LBound(Args) + 1 = 0 Then
    StringConcat = vbNullString
    Exit Function
End If


For N = LBound(Args) To UBound(Args)
    ''''''''''''''''''''''''''''''''''''''''''''''''
    ' Loop through the Args
    ''''''''''''''''''''''''''''''''''''''''''''''''
    If IsObject(Args(N)) = True Then
        '''''''''''''''''''''''''''''''''''''
        ' OBJECT
        ' If we have an object, ensure it
        ' it a Range. The Range object
        ' is the only type of object we'll
        ' work with. Anything else causes
        ' a #VALUE error.
        ''''''''''''''''''''''''''''''''''''
        If TypeOf Args(N) Is Excel.Range Then
            '''''''''''''''''''''''''''''''''''''''''
            ' If it is a Range, loop through the
            ' cells and create append the elements
            ' to the string S.
            '''''''''''''''''''''''''''''''''''''''''
            For Each R In Args(N).Cells
                If SkipEmpty = True Then
                    If R.Text <> vbNullString Then
                        S = S & R.Text & Sep
                    End If
                Else
                    S = S & R.Text & Sep
                End If
            Next R
        Else
            '''''''''''''''''''''''''''''''''
            ' Unsupported object type. Return
            ' a #VALUE error.
            '''''''''''''''''''''''''''''''''
            StringConcat = CVErr(xlErrValue)
            Exit Function
        End If
    
    ElseIf IsArray(Args(N)) = True Then
        
        On Error Resume Next
        '''''''''''''''''''''''''''''''''''''
        ' ARRAY
        ' If Args(N) is an array, ensure it
        ' is an allocated array.
        '''''''''''''''''''''''''''''''''''''
        IsArrayAlloc = (Not IsError(LBound(Args(N))) And _
            (LBound(Args(N)) <= UBound(Args(N))))
        On Error GoTo 0
        If IsArrayAlloc = True Then
            ''''''''''''''''''''''''''''''''''''
            ' The array is allocated. Determine
            ' the number of dimensions of the
            ' array.
            '''''''''''''''''''''''''''''''''''''
            NumDims = 1
            On Error Resume Next
            Err.Clear
            NumDims = 1
            Do Until Err.Number <> 0
                LB = LBound(Args(N), NumDims)
                If Err.Number = 0 Then
                    NumDims = NumDims + 1
                Else
                    NumDims = NumDims - 1
                End If
            Loop
            ''''''''''''''''''''''''''''''''''
            ' The array must have either
            ' one or two dimensions. Greater
            ' that two caues a #VALUE error.
            ''''''''''''''''''''''''''''''''''
            If NumDims > 2 Then
                StringConcat = CVErr(xlErrValue)
                Exit Function
            End If
            If NumDims = 1 Then
                For M = LBound(Args(N)) To UBound(Args(N))
                    If Args(N)(M) <> vbNullString Then
                        If SkipEmpty = True Then
                            If Args(N)(M) <> vbNullString Then
                                S = S & Args(N)(M) & Sep
                            End If
                        Else
                            S = S & Args(N)(M) & Sep
                        End If
                    End If
                Next M
                
            Else
                For RN = LBound(Args(N), 1) To UBound(Args(N), 1)
                    For CN = LBound(Args(N), 2) To UBound(Args(N), 2)
                        If SkipEmpty = True Then
                            If Args(N)(RN, CN) <> vbNullString Then
                                S = S & Args(N)(RN, CN) & Sep
                            End If
                        Else
                            S = S & Args(N)(RN, CN) & Sep
                        End If
                    Next CN
                Next RN

            End If
        Else
            S = S & Args(N) & Sep
        End If
    Else
        If SkipEmpty = True Then
            If Args(N) <> vbNullString Then
                S = S & Args(N) & Sep
            End If
        Else
            S = S & Args(N) & Sep
        End If
    End If
Next N

'''''''''''''''''''''''''''''
' Remove the trailing Sep
'''''''''''''''''''''''''''''
If Len(Sep) > 0 Then
    S = Left(S, Len(S) - Len(Sep))
End If

StringConcat = S

End Function


download You can download the file with all the example code on this page.
ShortFadeBar
LastUpdate This page last updated: 14-June-2009.

Created by Chip Pearson at Pearson Software Consulting, LLC
Email: chip@cpearson.com Before emailing me, please read this page
http://www.cpearson.com/Excel/stringconcatenation.aspx
Copyright © 1997 - 2009, Charles H. Pearson

Submit bug information or errors on the Bug And Error Report Page.



 


sectionbreak
Essential Tools For Developers


  

Essential Tools For Financial Analysts And Accounting Professionals

  
Ready


Advertise Your Product On This Site