PDA

View Full Version : Search and Highlight First Instance of Capitalized Terms



Beginner2015
03-15-2015, 01:45 PM
Hi - I'm a bit of a beginner at vba coding and was hoping someone guide/help me out. I am trying to highlight all words that start with a capital letter, but not the words at the beginning of a paragraph or sentence. So far I have figured out how to highlight all words that start with a capital letter that are not after a paragraph or sentence, but I can't figure out how to only highlight the first instance of the word. In other words, if the word "Example" is used many times in the document, I only want the first instance of the word "Example" to be highlighted. Using mostly the record macro function in word, here is what I have come up with so far:

Options.DefaultHighlightColorIndex = wdYellow
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Highlight = True
With Selection.Find
.Text = "<[A-Z]*>"
.Replacement.Text = "^&"
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True

End With
Selection.Find.Execute Replace:=wdReplaceAll
Options.DefaultHighlightColorIndex = wdNoHighlight
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Highlight = True
With Selection.Find
.Text = "^13<[A-Z]*>"
.Replacement.Text = "^&"
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True

End With
Selection.Find.Execute Replace:=wdReplaceAll
With Selection.Find
.Text = "([.?]) <[A-Z]*>"
.Replacement.Text = "^&"
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True

End With

Thanks in advance for the help. Sorry if I'm being obtuse in any way, I'm a bit of a beginner. Happy to clarify in any way if needed. Thanks!

gmaxey
03-16-2015, 04:08 AM
This will get you close. The problem is Word doesn't really know what a sentence is and cap words following an abbreviation e.g., Mr. Smith won't get highlighted:


Sub ScratchMacro()
'A basic Word macro coded by Greg Maxey
Dim oRng As Word.Range
Dim colUnique As New Collection
Set oRng = ActiveDocument.Range
With oRng.Find
.Text = "([!^13\!.?]) <[A-Z]*>"
.Replacement.Text = "^&"
.Forward = True
.Wrap = wdFindStop
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
While .Execute
oRng.MoveStart wdCharacter, 2
On Error Resume Next
colUnique.Add oRng.Text, oRng.Text
If Err.Number = 0 Then
oRng.HighlightColorIndex = wdBrightGreen
End If
oRng.Collapse wdCollapseEnd
Wend
End With
End Sub