Question

I have a csv with 2 columns

sku,color
001,blue
001,red
001,pink
001,yellow
002,blue
002,red
002,pink
002,yellow
etc..

how can i create a new cell and combine the colors based on sku number? like this:

sku,combinedColors
001,"blue,red,pink,yellow"
002,"blue,red,pink,yellow"

thanks

Was it helpful?

Solution

There isn't a single formula that will do this and a macro is the best way. But there is a way to do it with 2 formulas.

Open the CSV in Excel and you MUST sort column A ascending/descending.

Then in C2 , add this formula and drag it down

=IF(A2<>A1,B2,C1 & "," & B2)


in D2 ,add this formula and drag it down

=IF(A2<>A3,CONCATENATE(A2,",""",C2,""""),"")


Put the Autofilter on Row 1 and select NON BLANKS in column D. You can then copy column D as you wanted!

OTHER TIPS

You can do this with a VBA Macro. To enter this Macro (Sub), alt-F11 opens the Visual Basic Editor. Ensure your project is highlighted in the Project Explorer window. Then, from the top menu, select Insert/Module and paste the code below into the window that opens.

You may want to make some changes depending on the location of your source data and where you want the results written. The macro assumes your source data is in columns A:B with a header row, and that your results will be written in columns D:E

I also assumed, since this is tagged with Excel, that you have imported the csv data into excel and you want the results in two columns.

To use this Macro (Sub), alt-F8 opens the macro dialog box. Select the macro by name, and .

Option Explicit
Sub ConcatColorsBySKU()
    Dim colSKU As Collection
    Dim vSrc As Variant, vRes() As Variant
    Dim I As Long, J As Long
    Dim rRes As Range
vSrc = Range("A1", Cells(Rows.Count, "A").End(xlUp)).Resize(columnsize:=2)
Set rRes = Range("D1")

'Unique SKU's
Set colSKU = New Collection
On Error Resume Next
For I = 2 To UBound(vSrc)
    colSKU.Add Item:=CStr(vSrc(I, 1)), Key:=CStr(vSrc(I, 1))
Next I
On Error GoTo 0

'Results Array
ReDim vRes(1 To colSKU.Count + 1, 1 To 2)
vRes(1, 1) = "SKU"
vRes(1, 2) = "Combined Colors"
For I = 1 To colSKU.Count
    vRes(I + 1, 1) = colSKU(I)
    For J = 2 To UBound(vSrc)
        If vSrc(J, 1) = vRes(I + 1, 1) Then _
            vRes(I + 1, 2) = vRes(I + 1, 2) & ", " & vSrc(J, 2)
    Next J
    vRes(I + 1, 2) = Mid(vRes(I + 1, 2), 2)
Next I

Set rRes = rRes.Resize(UBound(vRes, 1), UBound(vRes, 2))
rRes.NumberFormat = "@"
rRes = vRes
rRes.EntireColumn.AutoFit

End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top