Home |
Search |
Today's Posts |
#1
Posted to microsoft.public.excel.programming
|
|||
|
|||
sorting text in a string
How can I sort a string of text in VBA. For Example -
v_text = "gbc3d1aef2" should be sorted to "abcdefg123" Cheers RTP |
#2
Posted to microsoft.public.excel.programming
|
|||
|
|||
sorting text in a string
On Sat, 25 Aug 2007 10:56:02 -0700, RTP wrote:
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 |
#3
Posted to microsoft.public.excel.programming
|
|||
|
|||
sorting text in a string
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 On Aug 25, 10:56 am, RTP wrote: How can I sort a string of text in VBA. For Example - v_text = "gbc3d1aef2" should be sorted to "abcdefg123" Cheers RTP |
Reply |
Thread Tools | Search this Thread |
Display Modes | |
|
|
Similar Threads | ||||
Thread | Forum | |||
Change 3 letter text string to a number string | Excel Discussion (Misc queries) | |||
Sorting By Largest Value In A String | Excel Programming | |||
Splitting a text string into string and number | Excel Discussion (Misc queries) | |||
string sorting problem | Excel Programming | |||
sorting data in string | Excel Programming |