Link to home
Start Free TrialLog in
Avatar of Steve_Brady
Steve_BradyFlag for United States of America

asked on

Excel VBA code needs a small (I hope) tweak please

Hello,

Sometime ago, I received a VBA solution from some "EEEE"*

        Concatenate in Excel without entering every cell reference

for the purpose of 1) concatenating the contents of multiple cells when the number of involved cells is too great to practically use the common concatenating Excel formula:

        =A1&A2&A3&A4&...etc.

and 2) being able to select a custom delimiter.

The code in the solution is as follows:

Function strcat(rng As Range, Optional dlm As String = ",", Optional bUseFormat As Boolean = True)
Dim cel As Range
For Each cel In rng
If cel.Value <> "" Then strcat = strcat & dlm & IIf(bUseFormat, cel.Text, cel.Value)
Next cel
strcat = Mid$(strcat, Len(dlm))
End Function

Open in new window

and the function to enter into the spreadsheet is here:

=strcat(Desired_Range,Custom_Delimiter)

Open in new window

Something I noticed just recently that I had not noticed previously is that when using this code, a delimiter is inserted prior to the first cell's contents. For example, if the contents of five cells to be concatenated are:

        dog
        cat
        bird
        fish
        iguana

respectively and the custom delimiter is a closing curly bracket "}", the result would be displayed as follows:

        }dog}cat}bird}fish}iguana

with the first character being a delimiter.

Could someone tweak the above code so that this initial delimiter is not included in the result display?

Thanks


* EEEE = Excellent Experts-Exchange Experts
ASKER CERTIFIED SOLUTION
Avatar of Saqib Husain
Saqib Husain
Flag of Pakistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
EEEEE   Excellent Experts-Exchange Excel Experts
Avatar of Steve_Brady

ASKER

One additional note:

The custom delimiter is interestingly not included when all of the cells in the defined range are empty.
>>EEEEE   Excellent Experts-Exchange Excel Experts

Touché  :)
Correction:

The thread title & link included in the original question above is incorrect. The correct title & link is the following:

        Abbreviation to shorten lengthy repetitive Excel formulas
>>ssaiqbh

If cel.Value <> "" Then strcat = strcat & IIf(strcat = "", "", dlm) & IIf(bUseFormat, cel.Text, cel.Value)


Thanks Syed—just what I needed. Of course you would know, since you wrote the original!  :)