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
|