Sorting alphabetically in Word -- by word inside phrase or sentence. Macro or VBA?

Hello!

I'm using Office 365 on a Windows PC.

The task at hand involves creating a long list of phrases and individual sentences, then applying a style to a specific word in each phrase or sentence. The result should be to "boldify" (ha!) that specific word.

Then I'll need to alphabetically sort this list, based not on the first letter of the phrase/sentence, but by the word which was selected and bolded in each separate phrase or sentence.

It might look something like this before it's sorted:

slow and steady wins the race

dogs and cats

as soon as possible

partly cloudy with a chance of rain

and something like this after it's sorted:

dogs and cats

partly cloudy with a chance of rain

as soon as possible

slow and steady wins the race

Do any of you super-smart folks have a suggestion about how to accomplish this?

Thanks!!

Answer
Answer

Not very elegant, but then I am not so super-smart.

Provided that each of your phrases constitutes a complete paragraph then perhaps something like this:

Sub ScratchMacro()
'A basic Word macro coded by Greg Maxey
Dim lngIndex As Long
Dim oRng As Word.Range
Dim arrWords() As String
Dim oCol As New Collection
  With ActiveDocument
    ReDim arrWords(.Paragraphs.Count - 1, 1)
    For lngIndex = 1 To .Paragraphs.Count
      Set oRng = .Paragraphs(lngIndex).Range
      With oRng.Find
        .Font.Bold = True
        .MatchWildcards = True
        If .Execute Then
          arrWords(lngIndex - 1, 0) = oRng.Text
          arrWords(lngIndex - 1, 1) = ActiveDocument.Paragraphs(lngIndex).Range.Text
          oRng.Collapse wdCollapseEnd
        End If
      End With
    Next
    WordBasic.SortArray arrWords
    .Range.Delete
    For lngIndex = 0 To UBound(arrWords)
      .Range.InsertAfter arrWords(lngIndex, 1)
      Set oRng = .Paragraphs(lngIndex + 1).Range
      With oRng.Find
        .Text = arrWords(lngIndex, 0)
        If .Execute Then
          oRng.Font.Bold = True
        End If
      End With
    Next
  End With
End Sub

Greg Maxey
***
Death smiles at us all, but all a man can do is smile back.


For more help with Word visit:
http://gregmaxey.com/word_tips.html

Was this reply helpful?

Sorry this didn't help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

 
 

Question Info


Last updated February 13, 2022 Views 920 Applies to: