top of page

Word Macro to Collect Sentences Containing a Specified String

Tonight's tip is on a macro that can be used in Microsoft Word to collect all sentences which contain a given phrase.

As you can see in this example there are references in a brief to produced documents containing the letter prefix, 'GAI'. We enter the below macro by pressing ALT + F11 and then right clicking on the name of the file in the project list and choosing Insert . . . Module.

Edit the macro by putting the term you want to search for on the line reading: .Text = "GAI" ' the word I am looking for

The only other change you need to make is to set the file path on the line beginning, "Set objSheet = appExcel.workbooks.Open" to an Excel file that you have created in a destination folder.

The results are written to the Excel file.

Option Explicit Sub FindWordCopySentence() Dim appExcel As Object Dim objSheet As Object Dim aRange As Range Dim intRowCount As Integer intRowCount = 1 Set aRange = ActiveDocument.Range With aRange.Find Do .Text = "GAI" ' the word I am looking for .Execute If .Found Then aRange.Expand Unit:=wdSentence aRange.Copy aRange.Collapse wdCollapseEnd If objSheet Is Nothing Then Set appExcel = CreateObject("Excel.Application") 'Change the file path to match the location of your test.xls Set objSheet = appExcel.workbooks.Open("C:\wordmacro\list.xlsx").Sheets("Sheet1") intRowCount = 1 End If objSheet.Cells(intRowCount, 1).Select objSheet.Paste intRowCount = intRowCount + 1 End If Loop While .Found End With If Not objSheet Is Nothing Then appExcel.workbooks(1).Close True appExcel.Quit Set objSheet = Nothing Set appExcel = Nothing End If Set aRange = Nothing End Sub

Thanks to Lucas for posting this macro here:

bottom of page