Forum Discussion
Search a specific string in URLs across multiple Word documents
I would like to search for a specific string ("urldefense") in URLs across multiple Word documents that are all in the same folder. (I use Word on a Windows 11 desktop.) If it's possible to do this, I'd be grateful for directions.
pjs
3 Replies
- Charles_KenyonBronze Contributor
Here are two utilities for doing batch operations on files in a folder:
Similar questions elsewhere:
- cdrgregCopper Contributor
Sub BacthFindI() 'Compiled by Greg Maxey Dim strFileName As String Dim strFolderPath As String Dim oDoc As Document Dim oRng As Range Dim lngCount As Long Application.ScreenUpdating = True 'Specify folder containing files strFolderPath = "D:\Batch\Test Batch\" 'Loop through all the files of *.doc type in the directory by using Dir$ function strFileName = Dir$(strFolderPath & "*.doc*") Do While strFileName <> "" Set oDoc = Documents.Open(strFolderPath & strFileName, , , False, , , , , , , , False) If Not ActiveWindow.View.ShowFieldCodes = True Then oDoc.Fields.ToggleShowCodes Set oRng = oDoc.Range With oRng.Find .Text = "urldefense" Do While .Execute lngCount = lngCount + 1 Loop End With oDoc.Close wdDoNotSaveChanges strFileName = Dir$ Loop MsgBox lngCount Application.ScreenUpdating = True End SubTo search and count. Use the above.
To search and revise, use something like the following:
Sub BacthFindII() 'Compiled by Greg Maxey Dim strFileName As String Dim strFolderPath As String Dim oDoc As Document Dim oRng As Range Application.ScreenUpdating = False 'Specify folder containing files strFolderPath = "D:\Batch\Test Batch\" 'Loop through all the files of *.doc type in the directory by using Dir$ function strFileName = Dir$(strFolderPath & "*.doc*") Do While strFileName <> "" Set oDoc = Documents.Open(strFolderPath & strFileName, , , False, , , , , , , , False) If Not ActiveWindow.View.ShowFieldCodes = True Then oDoc.Fields.ToggleShowCodes Set oRng = oDoc.Range With oRng.Find .Text = "urldefense" .Replacement.Text = "someothertext" .Execute Replace:=wdReplaceAll End With oDoc.Fields.ToggleShowCodes oDoc.Close wdSaveChanges strFileName = Dir$ Loop Application.ScreenUpdating = True lbl_Exit: Exit Sub End Sub You can search for a specific string, such as "urldefense," across multiple Word documents stored in a single folder. While Microsoft Word does not provide a native feature for multi‑document search, this can be accomplished using either Windows Search or a VBA macro within Word to automate the process.
https://learn.microsoft.com/en-us/office/vba/api/overview/
https://learn.microsoft.com/en-us/answers/questions/5108893/how-to-set-up-searching-within-microsoft-office-fi