Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Concatenate multi fields with Commas 2

Status
Not open for further replies.

smatthews

IS-IT--Management
Jul 27, 2001
108
US
Hello,

I am able to concatenate multiple fields but I would like to put a comma between the fields. However if the field is blank I just get the comma. Also, I am converting a code to a word.
Eg.
A B C = Red,White,Blue
A C = Red,Blue

Any suggestions?

Thanks in advance.
 
Use an IIf( ) function to determine whether the column has a value. If it is concatenate only the value; if not, concatenate a comma plus the value.
Code:
SELECT
            colA +
            IIf( colB = '', colB, ','+colB ) +
            IIf( colC = '', colC, ','+colC )
 

rac2's solution fails if A is not present...
Code:
IIf(Left(replace([A] & "," & [B] & "," & [C],",,",","),1)=",",Right(replace([A] & "," & [B] & "," & [C],",,",","),Len(replace([A] & "," & [B] & "," & [C],",,",","))-1),
IIf(Right(replace([A] & "," & [B] & "," & [C],",,",","),1)=",",Left(replace([A] & "," & [B] & "," & [C],",,",","),Len(replace([A] & "," & [B] & "," & [C],",,",","))-1),
[A] & "," & [B] & "," & [C]
))
If you don't have a function for Replace, paste this in a VBA module ...
Code:
Function Replace(Str As String, sFind As String, sRepl As String) As String
    Dim i
    i = InStr(Str, sFind)
    If i > 0 Then
        Replace = Left(Str, i - 1) & sRepl & Right(Str, Len(Str) - Len(sFind) - (i - 1))
    Else
        Replace = Str
    End If
End Function



Skip,

[glasses] [red]Be advised:[/red]When Viscounts were guillotined just as they were disclosing where their jewels were hidden, it shows to go that you should...
Never hatchet your Counts before they chicken! [tongue]
 
Thanks so much Skip. I was trying to figure out how to get rid of that preceeding comma.

 
It's more complicated than it looks.

Here's the essence (BAM!)
Code:
[b]
IIf(Left(X,1)=",",Right(X,Len(X)-1),
IIf(Right(X,1)=",",Left(X,Len(X)-1),
Y
))[/b]

where [b][ignore]

X = replace(Y,",,",",")
Y = [A] & "," & [B] & "," & [C][/ignore][/b]

Skip,

[glasses] [red]Be advised:[/red]When Viscounts were guillotined just as they were disclosing where their jewels were hidden, it shows to go that you should...
Never hatchet your Counts before they chicken! [tongue]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top