R – Highlighting search terms in an MS Word document

full-text-searchhighlightingms-word

We have a project where we need to provide search over a collection of Word documents through a web-based interface. The client would like for the search terms to be highlighted when a user opens a document.

Is there a way to do this directly in Word when opening a document? The only alternative we can come up with is to convert the Word documents to HTML and display that.

Just for background, we're currently using Windows SharePoint Services for document searching.

Best Answer

You could do that using Word's Highlight feature. However, to use the feature you will have to use Word automation on either server-side or client-side.

A script in VBA for highlighting a search term could look like this:

Sub Highlight(oDoc As Word.Document, term As String)

    With oDoc.Range.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Replacement.Highlight = True
        .Text = term
        .Replacement.Text = term
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute Replace:=wdReplaceAll
    End With

End Sub

The script does a search-and-replace and applies highlighting to the found text. If you have any questions on how to automate Word best, e.g. in a server environment, don't hesitate to ask.

Related Topic