View Single Post
 
Old 10-15-2012, 09:33 AM
RBLampert RBLampert is offline Windows 7 64bit Office 2010 64bit
Novice
 
Join Date: Oct 2012
Posts: 9
RBLampert is on a distinguished road
Question Find and highlight all words ending in -ly

It seems like this ought to be really easy. I’m trying to write a macro for MS Word 2010 that will find all words ending in –ly in a document and highlight them. The code below will find the first such word and highlight it, but stops there. The commented-out Do loop doesn’t end if it’s run.
Code:
Sub Highlight_adverb() 
     '
     ' Highlight_adverb Macro
     ' Finds and highlights words that end in ly.
     '
     ' Go to the beginning of the piece being checked
     '
    Selection.HomeKey Unit:=wdStory 
     '
     ' Clear any previous search targets
     '
    Selection.Find.ClearFormatting 
     '
     ' Create Do loop that runs until the end of the document is reached
     '
     ' Do
     '
     ' Find example of word ending in "ly ", select the whole word, and highlight it
     '
    With Selection.Find 
        .Text = "ly" 
        .Forward = True 
        .Wrap = wdFindStop 
        .MatchSuffix = True 
    End With 
    Selection.Find.Execute 
    Selection.MoveLeft Unit:=wdWord, Count:=1 
    Selection.MoveRight Unit:=wdWord, Count:=1, Extend:=wdExtend 
    Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend 
    Options.DefaultHighlightColorIndex = wdTurquoise 
    Selection.Range.HighlightColorIndex = wdTurquoise 
     '
     ' Move forward one word to avoid reselecting the word just highlighted
     '
    Selection.MoveRight Unit:=wdWord, Count:=1 
     ' Selection.Find.Execute Replace:=wdReplaceAll
     '
     ' ...and loop
     '
     ' Loop While Selection.EndOf(Unit:=wdStory)
End Sub
This code (below), on the other hand, finds And highlights all –ly suffixes but Not the complete word.
Code:
Sub highlight_ly_2() 
     '
     ' highlight_ly_2 Macro
     '
     ' Go to the beginning of the piece being checked
     '
    Selection.HomeKey Unit:=wdStory 
     '
     ' Find and highlight all ly suffixes
     '
    With Selection.Find 
        .ClearFormatting 
        .Replacement.ClearFormatting 
        .Replacement.Highlight = True 
        .Text = "ly" 
        .Replacement.Text = "ly" 
        .Forward = True 
        .Wrap = wdFindContinue 
        .Format = True 
        .MatchSuffix = True 
    End With 
    Selection.Find.Execute Replace:=wdReplaceAll      
End Sub
How do I get the code to do both? I feel like I’m missing one simple command but have no idea what it is.

Last edited by macropod; 10-15-2012 at 05:34 PM. Reason: Added code tags & formatting
Reply With Quote