View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
Mike H Mike H is offline
external usenet poster
 
Posts: 11,501
Default how to sort a string?

Hi,

This works on A1 in the activesheet. It cheats by copying the string to a
new range, sorting it then putting it back. It uses column IV as the
temporary sort range so any data in that column will be lost.


Sub Sonic()
Dim x As Long, LastRow As Long
Dim V As Variant
Dim S As String, newstring As String
Columns(256).ClearContents
S = Range("A1").Value
V = Split(S, ",")
Application.ScreenUpdating = False
For x = 0 To UBound(V)
Cells(x + 1, 256).Value = V(x)
Next
LastRow = Cells(Cells.Rows.Count, "IV").End(xlUp).Row
Worksheets("Sheet1").Sort.SortFields.Clear
Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("IV1"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("IV1:IV" & LastRow)
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Set MyRange = Range("IV1:IV" & LastRow)
For Each c In MyRange
newstring = newstring & c.Value & ","
Next
Range("a1").Value = Left(newstring, Len(newstring) - 1)
Columns(256).ClearContents
Application.ScreenUpdating = True
End Sub



Mike
"CG Rosen" wrote:

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