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
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.
Do More in Less Time! Are you ready to harness the full power of Word 2013 to create professional documents? In this comprehensive guide you'll learn the skills and techniques for efficiently building the documents you need for your professional and your personal life. Check out Word 2013 In Depth today!
Want the ribbon to be minimized for a particular document? Word may not allow you to get the exact result you want, as ...
Discover MoreWould you like a countdown value of some type to appear in your document? You can create your own through the use of a ...
Discover MoreDo you need to copy, within a macro, a range of pages? Because pages can be so fluid in Word, this can be a bit tricky. ...
Discover MoreFREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."
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
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.
Visit the WordTips channel on YouTube
FREE SERVICE: Get tips like this every week in WordTips, a free productivity newsletter. Enter your address and click "Subscribe."
Copyright © 2024 Sharon Parq Associates, Inc.
Comments