View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Ron Rosenfeld[_2_] Ron Rosenfeld[_2_] is offline
external usenet poster
 
Posts: 1,045
Default Sort in striing?

On Thu, 22 Nov 2012 11:21:55 +0100, "Charlotte E." wrote:

Hi,


I have a string variable, containing names seperated by a comma, like:

NameString = "Peter, Dan, Hans, Carl, Bruce" etc...

I would like the string to by sorted, by the names between the commas,
so my string end up like:

NameString = "Bruce, Carl, Dan, Hans, Peter" etc...

And to make things worse, the number of commas/names can be different
from time to time...

Can anyone help me acomplish this?


Thanks in advance,

CE


There are lots of VBA sort routines out there. Here's one:

===========================
Option Explicit
Sub SortString()
Dim NameString As String
Dim v As Variant
NameString = "Peter, Dan, Hans, Carl, Bruce"
v = Split(NameString, ", ")
Quick_Sort v, LBound(v), UBound(v)

Debug.Print Join(v, ", ")
End Sub


'--------------------------------------------
Sub Quick_Sort(ByRef SortArray As Variant, ByVal First As Long, ByVal Last As Long)
Dim Low As Long, High As Long
Dim Temp As Variant, List_Separator As Variant
Low = First
High = Last
List_Separator = SortArray((First + Last) / 2)
Do
Do While (SortArray(Low) < List_Separator)
Low = Low + 1
Loop
Do While (SortArray(High) List_Separator)
High = High - 1
Loop
If (Low <= High) Then
Temp = SortArray(Low)
SortArray(Low) = SortArray(High)
SortArray(High) = Temp
Low = Low + 1
High = High - 1
End If
Loop While (Low <= High)
If (First < High) Then Quick_Sort SortArray, First, High
If (Low < Last) Then Quick_Sort SortArray, Low, Last
End Sub
=================================