sorting text in a string

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

How can I sort a string of text in VBA. For Example -

v_text = "gbc3d1aef2"

should be sorted to "abcdefg123"

Cheers
RTP
 
How can I sort a string of text in VBA. For Example -

v_text = "gbc3d1aef2"

should be sorted to "abcdefg123"

Cheers
RTP

There are a number of different sort algorithms. Here's one courtesy of MS.

==================================================
Option Explicit
Sub foo()
Const v_text As String = "gbc3d1aef2"
Dim t(), t1
Dim i As Long

ReDim t(Len(v_text) - 1)
For i = 0 To UBound(t)
t(i) = Mid(v_text, i + 1, 1)
Next i

BubbleSort t

For i = 0 To UBound(t)
t1 = t1 & t(i)
Next i

Debug.Print v_text, t1
End Sub
'-------------------------------------------------
Private Sub BubbleSort(TempArray As Variant)
Dim temp As Variant
Dim i As Integer
Dim NoExchanges As Integer

' Loop until no more "exchanges" are made.
Do
NoExchanges = True

' Loop through each element in the array.
For i = 0 To UBound(TempArray) - 1

' If the element is greater than the element
' following it, exchange the two elements.
If TempArray(i) > TempArray(i + 1) Then
NoExchanges = False
temp = TempArray(i)
TempArray(i) = TempArray(i + 1)
TempArray(i + 1) = temp
End If
Next i
Loop While Not (NoExchanges)
End Sub
======================================
--ron
 
A quick and dirty solution:

Sub SortThisText()
Dim SortedLetters(255) As String

TextToSort = Application.Selection
SortedText = ""

For i = 1 To Len(TextToSort)
CurrentChar = Mid(TextToSort, i, 1)
SortedLetters(Asc(CurrentChar)) = SortedLetters(Asc(CurrentChar))
& CurrentChar
Next

For i = 1 To 255
SortedText = SortedText & SortedLetters(i)
Next

MsgBox (SortedText)
End Sub

This sorts the text based on ASCII codes and pops a message box with
the sorted text. You will need to be careful that ASCII order is what
you want - in your example you wanted numbers to come after letters so
that would need some more logic in the code to achieve that.

HTH
UKMatt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top