Sentences Containing a Search Term

Written by Allen Wyatt (last updated December 30, 2023)
This tip applies to Word 2007, 2010, 2013, 2016, 2019, Word in Microsoft 365, and 2021


3

Sara can use the search capabilities of Word to search for terms, such as "garrison." However, she would like to compile the search results, showing the entire sentence in which the found search term exists. Sara wonders if there is a method or tool to compose such a compilation.

Fortunately, Word provides a way that you can step through all the sentences in a document using VBA. This means that you can create a macro to find sentences containing your search term. Here's a simple example:

Sub CompileSentences()
    Dim docThis As Document
    Dim docThat As Document
    Dim sRaw As String
    Dim sWanted As String
    Dim J As Long

    sWanted = InputBox("Search Term")
    sWanted = Trim(LCase(sWanted))

    If sWanted > "" Then
        Set docThis = ActiveDocument
        Set docThat = Documents.Add

        For J = 1 To docThis.Sentences.Count
            sRaw = docThis.Sentences(J).Text
            sRaw = Trim(LCase(sRaw))
            If InStr(sRaw, sWanted) > 0 Then
                Selection.TypeText Text:=docThis.Sentences(J)
                Selection.TypeParagraph
            End If
        Next J
    End If
End Sub

The macro uses a For...Next loop to step through each of the sentences in the active document and checks whether those sentences contain the search term. If it does, then the sentence is added to a new document. You may wonder why a For...Next loop is used rather than a For...Each loop. The reason is easy—VBA allows you to access the Sentences collection, but there is no Sentence object in VBA; all access must be done by index number, as in this macro.

The macro also doesn't check to make sure that the search term is an entire word or not. Thus, if the sentence contained the word "garrisoned," and you were searching for "garrison," then the sentence would be considered a positive result. This approach was purposeful in case you wanted to search for multi-word phrases, such as "red cap" or "carrying case."

Note that the user is prompted to input what the search term should be. The search is case insensitive, and leading and trailing spaces are ignored. If the user doesn't enter anything when prompted, then the macro is exited.

WordTips is your source for cost-effective Microsoft Word training. (Microsoft Word is the most popular word processing software in the world.) This tip (8564) applies to Microsoft Word 2007, 2010, 2013, 2016, 2019, Word in Microsoft 365, and 2021.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Two-Level Axis Labels

Need a chart that uses two lines for axis labels? It's easy to do if you know how to set up your data in the worksheet, ...

Discover More

Exporting Latitude and Longitude

A handy way to store latitude and longitude values in Excel is to treat them as regular time values. When it comes around ...

Discover More

Reversing Type

Most text appears black on white, not white on black. If you want to change this so that your type is reversed, here's a ...

Discover More

Comprehensive VBA Guide Visual Basic for Applications (VBA) is the language used for writing macros in all Office programs. This complete guide shows both professionals and novices how to master VBA in order to customize the entire Office suite for their needs. Check out Mastering VBA for Office 2010 today!

More WordTips (ribbon)

Adding a Full-Width Line in a Macro

The AutoFormat feature in Word allows you to type special character sequences (such as three dashes or three underscores) ...

Discover More

Determining the Length of a String

Need to find out in a macro how long a particular text string is? You can figure it out by using the Len function, ...

Discover More

Resetting Character Formatting in a Macro

Shortcut keys are a great way to apply styles to text in a document. You can easily create a shortcut key assignment for ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] (all 7 characters, in the sequence shown) in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 2 + 2?

2024-01-02 20:30:37

Ken Endacott

The advantage of using Find is that it can apply criteria such as only whole words whereas Instr() will give a hit if part of a word contains the string.

In stepping through a collection it is usually far quicker to use For Each… rather than index the collection, in the manuscript example 1.7 seconds verses 400 seconds. But not always, there are a couple of collections where indexing is quicker.


2024-01-02 10:35:52

Andrew

Also, searching is fast, so why not serially search for each occurrence of the term and then just extract the sentence containing the found text, such as, for example, calling "Selection.Sentences(1).Text"?

Paradoxically, if in the text, "Hello. The alphabet begins with ABC. Goodbye." after selecting the term "ABC" this call will return the whole middle sentence.

Note to Macro-ists: This is a useful technique in Word in general. Ranges and Selections have a quite a few collections besides Sentences that can be accessed to find the encompassing unit, e.g., Paragraphs, Sections, Tables, and more.


2024-01-01 04:07:04

Ken Endacott

It is incorrect to say that because there is no Sentence object it is not possible to access the Sentences collection.

Using a for…Next loop results in abysmally slow execution. It is over 200 times faster to use a For Each X… loop where X is a Range object. As an example, 1.7 seconds verses 400 seconds for a 75000 word manuscript document.

The macro CompileSentencesFast below uses the For Each... loop.

Sub CompileSentencesFast()
Dim docThis As Document
Dim docThat As Document
Dim sRaw As String
Dim sWanted As String
Dim J As Long
Dim aRange As Range

sWanted = InputBox("Search Term")
sWanted = Trim(LCase(sWanted))

If sWanted > "" Then
Set docThis = ActiveDocument
Set docThat = Documents.Add
For Each aRange In docThis.Sentences
sRaw = aRange.Text
If Right(sRaw, 1) = Chr(13) Then sRaw = Left(sRaw, Len(sRaw) - 1)
sRaw = Trim(LCase(sRaw))
If InStr(sRaw, sWanted) > 0 Then
Selection.TypeText Text:=sRaw
Selection.TypeParagraph
End If
Next aRange
End If

End Sub


This Site

Got a version of Word that uses the ribbon interface (Word 2007 or later)? This site is for you! If you use an earlier version of Word, visit our WordTips site focusing on the menu interface.

Videos
Subscribe

FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.