View Single Post
  #9   Report Post  
Posted to microsoft.public.excel.programming
Rick Rothstein Rick Rothstein is offline
external usenet poster
 
Posts: 5,934
Default Can you sort one cell or a string in vba?

Picky... picky... picky <g

Okay, this modification should work correctly...

Function SortCharacters(ByVal S As String) As String
Dim X As Long, Z As Long, Cnt As Long
ReDim C(1 To Len(S)) As Long
For X = 1 To Len(S)
For Z = 1 To Len(S)
If Mid(S, Z, 1) <= Mid(S, X, 1) Then C(X) = C(X) + 1
Next
Next
SortCharacters = String(Len(S), Chr$(1))
For X = 1 To Len(S)
Mid(SortCharacters, C(X), 1) = Mid(S, X, 1)
Next
For X = Len(S) - 1 To 1 Step -1
If Mid(SortCharacters, X, 1) = Chr$(1) Then
Mid(SortCharacters, X, 1) = Mid(SortCharacters, X + 1, 1)
End If
Next
End Function

I'm not sure how it would compare speedwise with your (or any other)
routine, but I don't think it will be a slouch by any means (that's a gut
feeling based on past experience with the "string stuffing" method I have
employed). Anyway, the assumed size of the text string the function would be
used with probably makes differences in efficiency moot.

--
Rick (MVP - Excel)


"RB Smissaert" wrote in message
...
Try this string:
"ZZYYyy22222211111"

Not that may suggestion is perfect, but very fast though :-)

RBS


"Rick Rothstein" wrote in message
...
Here is my attempt at a solution. Place the following in a general Module
(Insert/Module from the VB editor's menu bar)...

Function SortCharacters(S As String) As String
Dim X As Long, Z As Long, Cnt As Long
ReDim C(1 To Len(S)) As Long
For X = 1 To Len(S)
For Z = 1 To Len(S)
If Mid(S, Z, 1) < Mid(S, X, 1) Then C(X) = C(X) + 1
Next
Next
SortCharacters = Space(Len(S))
For X = 1 To Len(S)
Mid(SortCharacters, C(X) + 1, 1) = Mid(S, X, 1)
Next
End Function

Just call this function from your own code passing the text you want to
sort. As an example...

MyString = "14386ah"
MsgBox SortCharacters(MyString)

This function can also be used as a UDF (user defined function) on the
worksheet as well. As an example...

=SortCharacters(A1)

--
Rick (MVP - Excel)


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

Thanks
JOhn