Site icon Christopher Watkin

Research Hacks #26: A Macro to search for text across all open Word documents

Recently I have been working with multiple long Microsoft Word documents, and I have wanted to search for a particular string across all the open documents. So far I have had to search each ddocument separately, which is somewhat annoying.

So I asked ChatGPT to write a Visual Basic Macro to search across all open Word documents at once, and it obliged splendidly. Here it is:

Option Explicit
Sub SearchForString()
    Dim doc As Document
    Dim range As Range
    Dim searchString As String
  
    ' Prompt user for string to search for
    searchString = InputBox("Enter string to search for:")
   
    ' Loop through all open Word documents
    For Each doc In Application.Documents
        ' Search for string in document
        Set range = doc.Content
        With range.Find
            .Text = searchString
            .MatchWholeWord = True
            .MatchCase = False
            .Wrap = wdFindStop
            ' If string is found, select the range and display message box
            If .Execute = True Then
                range.Select
                MsgBox "String found in document: " & doc.Name
            End If
        End With
    Next doc
End Sub

To read all the research hacks posted to date, please click here.

To use this script, open a new Microsoft Word document and press Alt+F11 to open the Visual Basic Editor. Then, go to Insert > Module and paste the above code into the module.

Save the code, and return to the Word document. To run the script, press Alt+F8, select SearchForString, and click the Run button. You will be prompted to enter the string you want to search for, and the script will search for this string in all open Word documents. If the string is found in a document, a message box will be displayed indicating the name of the document where the string was found

Exit mobile version