how to sort a string?
"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
Try this macro:
Sub sort_string(source As Range, destination As Range)
Dim parts() As String
Dim sorted As String
parts = Split(source.Value, ",")
imax = UBound(parts)
For i = 0 To imax - 1
For j = i + 1 To imax
If parts(j) < parts(i) Then
tmp = parts(i)
parts(i) = parts(j)
parts(j) = tmp
End If
Next j
Next i
sorted = ""
For i = 0 To imax - 1
sorted = sorted & parts(i) & ","
Next i
sorted = sorted & parts(imax)
destination.Value = sorted
End Sub
Example:
sort_string Range("A1"), Range("B4")
will sort the string in cell A1 and put the result in cell B4
Hope this helps / Lars-Åke
|