View Single Post
  #6   Report Post  
Posted to microsoft.public.excel.programming
Peter T Peter T is offline
external usenet poster
 
Posts: 5,600
Default how to sort a string?

And here's another one, spoilt for choice !

Sub test()
Dim S As String, sorted As String
S = "bv-8,ok-3,bv-5,sk-1,bh-2,ok-9"
sorted = SortCommaSepString(S)

Debug.Print sorted ' bh-2,bv-5,bv-8,ok-3,ok-9,sk-1
End Sub

Function SortCommaSepString(ByVal strIn) As String
Dim i As Long, j As Long
Dim s1 As String, s2 As String
Dim arr() As String

arr = Split(strIn, ",")

For i = 0 To UBound(arr) - 1
For j = (i + 1) To UBound(arr)
s1 = arr(i)
s2 = arr(j)
If StrComp(s1, s2, vbTextCompare) = 1 Then
arr(i) = s2
arr(j) = s1
End If
Next j
Next i

SortCommaSepString = Join(arr, ",")

End Function


All posted examples will give similar results with the test sample. However
with different strings the results might be very different, as three
different comparison methods are used. Bob's will sort the way Excel does
though it means using cells. Otherwise for most string comparisons it's
better (I think) to use the StrComp function rather than simple greater/less
comparisons.

Regards,
Peter T


"CG Rosen" wrote in message
...
Hi Group

Trying to sort a string looking like:

bv-8,ok-3,bv-5,sk-1,bh-2,ok-9 etc

into:

bh-2,bv-5,bv-8,ok-3,ok-9,sk-1 etc

Grateful for some help.

Brgds

CG Rosen