Sentences Containing a Search Term

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


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, 2021, and Word in Microsoft 365.

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

Turning Off Line Numbering

Need to have line numbering turned off for a paragraph or two? You can accomplish the task by following these steps.

Discover More

Selecting an Entire Paragraph

Paragraphs are an elemental building block for documents. This tip explains the different ways you can select entire ...

Discover More

How Operators are Evaluated

Operators are used in formulas to instruct Excel what to do to arrive at a result. Not all operators are evaluated in the ...

Discover More

Discover the Power of Microsoft Office This beginner-friendly guide reveals the expert tips and strategies you need to skyrocket your productivity and use Office 365 like a pro. Mastering software like Word, Excel, and PowerPoint is essential to be more efficient and advance your career. Simple lessons guide you through every step, providing the knowledge you need to get started. Check out Microsoft Office 365 For Beginners today!

More WordTips (ribbon)

Determining the Current Directory

When creating macros, it is often necessary to know which directory is the default. Here's how you can find out by using ...

Discover More

Jumping to the Start or End of a Document

When creating macros, it is often necessary to move the insertion point around the document so that text can be processed ...

Discover More

Keeping Documents at a Single-Page View

Word allows you to display either a single page at a time or, with larger monitors, multiple pages. If Word displays your ...

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 one more than 9?

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.