Results 1 to 7 of 7

Thread: [RESOLVED] Alphabatize a string using VBA - For excel function

Hybrid View

  1. #1

    Thread Starter
    New Member
    Join Date
    Aug 2008
    Posts
    4

    Resolved [RESOLVED] Alphabatize a string using VBA - For excel function

    Hi!

    The program I am using is excel. What I am looking to do is alphabetize a string within a cell. Note, I do not wish to alphabetize a column of words.

    Here is an example. Let's say cell A1 contains a string like so:

    "The Law Firm of Cohen & Jaffe"

    I would like to alphabetize this whole string, within the cell so that it should read:

    "Cohen Firm Jaffe Law of The"

    Any garbage characters I would not worry about, I can always get rid of them using find and replace. The important thing, is to alphabetize the string.

    The purpose of this task, is because I need to match data from 2 different databases, but some fields on the other database, although similar, are off just by a little (such as, reverse ordering). That is why I cannot use a normal sort function in excel to match the two datasets. Thus, the reason why I need to alphabetize a string, within a cell.

    Thanks for your help!

  2. #2
    PowerPoster
    Join Date
    Dec 2004
    Posts
    25,618

    Re: Alphabatize a string using VBA - For excel function

    you could split the cell content into an array using space character, sort the array, then join the array back into the cell
    there are many examples for sorting an array in the vb6 forum or vb6 codebank

    you could make this into a custom worksheet function
    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete

  3. #3

    Thread Starter
    New Member
    Join Date
    Aug 2008
    Posts
    4

    Re: Alphabatize a string using VBA - For excel function

    I could do it that way, however I have about 8000 phrases (cells) to alphabetize, meaning, I would have to run the program 8000 times. So that method wouldn't be ideal. I need to sort each phrase within the cells using a VBA function as to save time. I just don't know how to create the function.

  4. #4

    Thread Starter
    New Member
    Join Date
    Aug 2008
    Posts
    4

    Re: Alphabatize a string using VBA - For excel function

    I found this code, but it doesn't work in VBA. Maybe you can help me tweak it to perform the desired results?

    Code:
        ' Takes any string, alphabetizes it, and returns the alphabetized string
        Private Function Alphabetize(ByVal originalString As String) As String
            Dim alphabetizedString As String = ""
            Dim tempString As String
            Dim Iterator As Integer
            Dim closestToA As Char
            Dim positionToRemove As Integer
            Dim charsToRemove As Integer
            Dim tempIterator As Integer
    
            tempString = originalString
            charsToRemove = tempString.Length
    
            ' Two For loops to work through the string; first one is to ensure
            ' removal of one character each pass; second one loops through
            ' all characters in the current temporary string
            For Iterator = 0 To charsToRemove - 1
                ' Set the character closest to a as equal to the first character
                ' of the temporary string
                closestToA = tempString.Chars(0)
                positionToRemove = 0
    
                For tempIterator = 1 To tempString.Length - 1
                    If tempString.Chars(tempIterator) < closestToA Then
                        closestToA = tempString.Chars(tempIterator)
                        positionToRemove = tempIterator
                    End If
                Next tempIterator
    
                ' Remove selected character from tempstring and append it to alphabetizedString
                tempString = tempString.Remove(positionToRemove, 1)
                alphabetizedString &= closestToA.ToString
            Next Iterator
    
            Return alphabetizedString
    
        End Function    ' Alphabetize

  5. #5
    PowerPoster
    Join Date
    Dec 2004
    Posts
    25,618

    Re: Alphabatize a string using VBA - For excel function

    try like this
    vb Code:
    1. Function alphasort(r As Range)
    2. Dim c() As String
    3. c = Split(r.Value)
    4. qs c, LBound(c), UBound(c)
    5. alphasort = Join(c)
    6. End Function
    7. Function qs(c() As String, ByVal First As Long, ByVal Last As Long)
    8.     Dim Low As Long, High As Long
    9.     Dim MidValue As String
    10.    
    11.     Low = First
    12.     High = Last
    13.     MidValue = c((First + Last) \ 2)
    14.    
    15.     Do
    16.         Do While c(Low) < MidValue
    17.             Low = Low + 1
    18.         Loop
    19.         Do While c(High) > MidValue
    20.             High = High - 1
    21.         Loop
    22.                 If Low <= High Then
    23. ''                    Swap C(High), C(Low)
    24.                 tempC = c(Low)
    25.                 c(Low) = c(High)
    26.                 c(High) = tempC
    27.                    
    28.                
    29.             Low = Low + 1
    30.             High = High - 1
    31.         End If
    32.     Loop While Low <= High
    33.    
    34.     If First < High Then qs c, First, High
    35.     If Low < Last Then qs c, Low, Last
    36.     qs = c
    37.  
    38. End Function
    use alphasort as a worksheet function, or modify the arguments to use in a loop through a range
    i tested this with your sample text, note it does not remove the "&" character, but returned
    & Cohen Firm Jaffe Law The of
    it would be pretty easy to remove any unwanted characters
    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete

  6. #6

    Thread Starter
    New Member
    Join Date
    Aug 2008
    Posts
    4

    Re: Alphabatize a string using VBA - For excel function

    This does the trick! Thanks very much, you saved me about 8000 lines of data to analyze

  7. #7
    Head Hunted anhn's Avatar
    Join Date
    Aug 2007
    Location
    Australia
    Posts
    3,669

    Re: [RESOLVED] Alphabatize a string using VBA - For excel function

    Try this (for small arrays, we don't worry about method of sorting):
    Code:
    Option Explicit
    
    Function Alphabetize(ByVal sText As String) As String
       Dim sWords() As String, sTemp As String
       Dim i As Long, j As Long, n As Long
       
       '-- clean up text
       For i = 1 To Len(sText)
          Select Case Mid$(sText, i, 1)
             Case " ", "a" To "z", "A" To "Z"
             Case Else: Mid$(sText, i, 1) = " "
          End Select
       Next
       '-- remove leading and trailing spaces
       sText = Trim(sText)
       '-- remove multi spaces
       Do While InStr(sText, "  ")
          sText = Replace(sText, "  ", " ")
       Loop
       '-- split text by space
       sWords = Split(sText)
       n = UBound(sWords)
       If n = 0 Then '-- only one word
          Alphabetize = sText
       Else
          '-- sort array
          For i = 0 To n - 1
             For j = i + 1 To n
                If sWords(i) > sWords(j) Then
                   sTemp = sWords(i)
                   sWords(i) = sWords(j)
                   sWords(j) = sTemp
                End If
             Next
          Next
          Alphabetize = Join(sWords, " ")
       End If
    End Function
    Usage:
    cell A2: The Law Firm of Cohen & Jaffe
    cell B2: =Alphabetize(A2)
    • Don't forget to use [CODE]your code here[/CODE] when posting code
    • If your question was answered please use Thread Tools to mark your thread [RESOLVED]
    • Don't forget to RATE helpful posts

    • Baby Steps a guided tour
    • IsDigits() and IsNumber() functions • Wichmann-Hill Random() function • >> and << functions for VB • CopyFileByChunk

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width