VBA Function to Alphabetize Multiple Strings within a Cell

ryancgarrett

Board Regular
Joined
Jun 18, 2011
Messages
122
I have data that is consolidated into single cells. I'd like to alphabetize the strings within the cells they are in:

Original DataAlphabetized Data
Orange,Apple,BananaApple,Banana,Orange
Grape,Apple,Grape,BananaApple,Grape,Grape,Banana
GrapeGrape
Apple,OrangeApple,Orange

<tbody>
</tbody>

Unsure of the easiest way to handle the alphabetizing bit here.
 

Excel Facts

Why does 9 mean SUM in SUBTOTAL?
It is because Sum is the 9th alphabetically in Average, Count, CountA, Max, Min, Product, StDev.S, StDev.P, Sum, VAR.S, VAR.P.
This UDF should do what you want
Code:
Function SortDelimitedString(unSortedString As String, _
    Optional Descending As Boolean, Optional Delimiter As String = ",") As String

    Dim strLeft As String, strRight As String
    Dim strPivot As String, Words As Variant
    Dim i As Long
    
    Words = Split(unSortedString, Delimiter)
    strPivot = Words(0)
    
    For i = 1 To UBound(Words)
        If (Words(i) < strPivot) Xor Descending Then
            strLeft = strLeft & Delimiter & Words(i)
        Else
            strRight = strRight & Delimiter & Words(i)
        End If
    Next i
    strLeft = Mid(strLeft, Len(Delimiter) + 1)
    strRight = Mid(strRight, Len(Delimiter) + 1)
    If strLeft <> vbNullString Then
        strPivot = SortDelimitedString(strLeft, Descending, Delimiter) & Delimiter & strPivot
    End If
    If strRight <> vbNullString Then
        strPivot = strPivot & Delimiter & SortDelimitedString(strRight, Descending, Delimiter)
    End If
    SortDelimitedString = strPivot
End Function
 
Upvote 0

Forum statistics

Threads
1,215,063
Messages
6,122,930
Members
449,094
Latest member
teemeren

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top