Consulting

Results 1 to 3 of 3

Thread: Request a macro

  1. #1

    Request a macro

    Hi

    I have a list like the following list in word 2013:

    word1
    word2
    word3
    .
    .
    .


    They should be sorted according to the last letter (Ascending)

    If two words have the same last letter, should be sorted according to the letter penultimate and so on.


    Thanks

  2. #2
    Select the list and run the following macro.

    Sub SortBackwards()
    Dim strText As String
    Dim oPara As Paragraph
    Dim oSel As Range
    Dim oRng As Range
        Set oSel = Selection.Range
        For Each oPara In oSel.Paragraphs
            Set oRng = oPara.Range
            oRng.End = oRng.End - 1
            strText = oRng.Text
            oRng.Text = StrReverse(strText)
        Next oPara
        oSel.Sort
        For Each oPara In oSel.Paragraphs
            Set oRng = oPara.Range
            oRng.End = oRng.End - 1
            strText = oRng.Text
            oRng.Text = StrReverse(strText)
        Next oPara
    lbl_Exit:
        Set oSel = Nothing
        Set oPara = Nothing
        Set oRng = Nothing
        Exit Sub
    End Sub
    Graham Mayor - MS MVP (Word) 2002-2019
    Visit my web site for more programming tips and ready made processes
    http://www.gmayor.com

  3. #3
    Microsoft Word MVP 2003-2009 VBAX Guru gmaxey's Avatar
    Joined
    Sep 2005
    Posts
    3,340
    Location
    Graham,

    You beat me to this one. I was pondering over it thinking I would use an array and then had to make short day trip. Here is another approach:

    Sub SortBackwardsII()
    Dim oRng As Range
    Dim arrWords() As String
    Dim lngIndex As Long
    Dim oPara As Paragraph
        ReDim arrWords(0)
        Set oRng = Selection.Range.Duplicate
        For Each oPara In oRng.Paragraphs
           arrWords(UBound(arrWords)) = StrReverse(oPara.Range.Words(1))
           ReDim Preserve arrWords(UBound(arrWords) + 1)
        Next oPara
        ReDim Preserve arrWords(UBound(arrWords) - 1)
        WordBasic.SortArray arrWords
        lngIndex = 0
        For Each oPara In oRng.Paragraphs
          oPara.Range.Words(1) = StrReverse(arrWords(lngIndex))
          lngIndex = lngIndex + 1
        Next oPara
    lbl_Exit:
       Exit Sub
    End Sub
    Greg

    Visit my website: http://gregmaxey.com

Posting Permissions

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