Pages

Sunday, January 29, 2012

How to Search and Highlight/Tag a string in Word VBA

How to Search Content for Specific String/Text using Word VBA

This action is performed often by programmers - there are couple of ways to do

1. Selection.Find
2. Content.Find

We will have a look at how to search a string, highlight the string and tag the same using Word VBA. This needs document to be open

Sub Highlight_Tag_Found_Word()

Dim sFindText As String

sFindText = "Olympics"

Selection.ClearFormatting

Selection.HomeKey wdStory, wdMove

Selection.Find.ClearFormatting

Selection.Find.Execute sFindText

 

Do Until Selection.Find.Found = False

        Selection.Range.HighlightColorIndex = wdPink
        
        Selection.InsertBefore "< FoundWord >"
        
        Selection.InsertAfter < /FoundWord >
        
        Selection.MoveRight
        
        Selection.Find.Execute

Loop

 

End Sub

No comments:

Post a Comment