LinkBack Thread Tools Search this Thread Display Modes
Prev Previous Post   Next Post Next
  #4   Report Post  
Posted to microsoft.public.excel.programming
external usenet poster
 
Posts: 2,452
Default Can you sort one cell or a string in vba?

If you are dealing with large strings and speed is important then you could
use code like this.
Not tested, but I think it will be faster than a bubblesort.

Sub test()

Dim str As String

str = "azyxwvutsrqponmlkjihgfedcba"
MsgBox SortString(str)

End Sub


Function SortString(strString As String) As String

Dim btArray() As Byte
Dim btArray2() As Byte

btArray = strString

btArray2 = CountingSortByte1D(btArray)

SortString = ByteArrayToString(btArray2)

End Function


Function ByteArrayToString(btArray() As Byte) As String

Dim sAns As String
Dim lPos As Long

sAns = StrConv(btArray, vbUnicode)
lPos = InStr(sAns, Chr(0))

If lPos 0 Then
sAns = Left(sAns, lPos - 1)
End If

ByteArrayToString = sAns

End Function


Function CountingSortByte1D(arrByte() As Byte) As Byte()

Dim i As Long
Dim LB As Long
Dim UB As Long
Dim arrCount() As Long
Dim arrByteSorted() As Byte
Dim lThisCount As Long
Dim lNext_Offset As Long

LB = LBound(arrByte)
UB = UBound(arrByte)

'Create the Counts array
ReDim arrCount(0 To 255)

'create the sorted return array
ReDim arrByteSorted(LB To UB \ 2) As Byte

'Count the items
For i = LB To UB Step 2
arrCount(arrByte(i)) = arrCount(arrByte(i)) + 1
Next i

'Convert the arrCount into offsets
lNext_Offset = LB

For i = 0 To 255
lThisCount = arrCount(i)
arrCount(i) = lNext_Offset
lNext_Offset = lNext_Offset + lThisCount
Next i

'Place the items in the sorted array
For i = LB To UB Step 2
arrByteSorted(arrCount(arrByte(i))) = arrByte(i)
arrCount(arrByte(i)) = arrCount(arrByte(i)) + 1
Next i

CountingSortByte1D = arrByteSorted

End Function



RBS



"John" wrote in message
...
Say you have a string="14386ah"
Is there a excel vba function that will sort the string?

Thanks
JOhn


 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules

Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Similar Threads
Thread Thread Starter Forum Replies Last Post
Please let Excel sort by string value within the cell/column. Kraig Excel Programming 2 July 24th 06 06:03 PM
Sort does not preserve string of additions HollywoodSam Excel Worksheet Functions 1 June 4th 06 04:29 PM
Convert a string value to numeric and sort mariomaf Excel Programming 2 January 5th 06 09:56 AM
Sort collection string keys John[_88_] Excel Programming 4 October 15th 05 01:40 PM
sort (on part of) string - originally posted under Tricky Sort Tom Ogilvy Excel Programming 0 August 6th 04 02:42 AM


All times are GMT +1. The time now is 03:50 PM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
Copyright ©2004-2025 ExcelBanter.
The comments are property of their posters.
 

About Us

"It's about Microsoft Excel"