Log in

View Full Version : Search and highlight formatted strings



amitrus
02-07-2013, 08:36 AM
Hi All,

I'm new at this, and trying to write a MSWord macro that will find, and then highlight (in yellow), certain kinds of text strings in a MSWord file.

(I searched the forum and couldn't find anything on this point.)

For example:

1) An italicized comma, followed by any non italicized character (even whitespace). Thus, for example:


The second comma in this sentence, which is italicized, should be highlighted by the desired macro.

2) A bolded character (of any kind, even whitespace), that is both preceded and followed by non-bolded characters. Thus, for example:


This first example sentence ends in a bolded punctuation mark. That first period should be highlighted.

3) Any word that is in SmallCaps, and is >4 letters long, but is not capitalized. I don't know how to do smallcaps in html... but imagine for a moment that the following text is in smallcaps in MSWord:

Imagine All of This Is in Small Caps. . . the Word "under" Should Be Highlighted Because It Is More Than Four Characters Long but is not Capitalized


Does anyone know whether this is possible? I know it's quite easy to find normal text-patterns, but adding formatting to those patterns seems to be tricky.

amitrus
02-07-2013, 01:43 PM
Cross-posted on vbforums.com/showthread.php?709233-MSWord-Searching-for-multi-formatted-text-strings&p=4339301#post4339301

macropod
02-07-2013, 08:27 PM
Perhaps:
Sub Demo()
Application.ScreenUpdating = False
Options.DefaultHighlightColorIndex = wdBrightGreen
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "<[a-z]{5,}>"
.Replacement.Text = "^&"
.Font.SmallCaps = True
.Forward = True
.Format = True
.MatchWildcards = True
.Replacement.Highlight = True
.Execute Replace:=wdReplaceAll
.ClearFormatting
.Replacement.ClearFormatting
.Text = ","
.Font.Italic = True
.Replacement.Text = ""
.Wrap = wdFindStop
.MatchWildcards = False
.Execute
End With
Do While .Find.Found
If .Characters.Last.Next.Font.Italic = False Then
.HighlightColorIndex = wdBlue
End If
.Collapse wdCollapseEnd
.Find.Execute
Loop
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "."
.Font.Bold = True
.Forward = False
.Execute
End With
Do While .Find.Found
If .Characters.Last.Next.Font.Bold = False Then
If .Characters.First.Previous.Font.Bold = False Then
.HighlightColorIndex = wdRed
End If
End If
.Collapse wdCollapseStart
.Find.Execute
Loop
End With
Application.ScreenUpdating = True
End Sub