defaultrush
New Member
- Joined
- Dec 14, 2022
- Messages
- 4
- Office Version
- 365
- Platform
- Windows
Public Sub Find_and_Replace_In_Word_Docs()
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
Dim docsFolder As String
Dim ws As Worksheet
Dim r As Long
docsFolder = "C:\path\to\docs\folder\" 'CHANGE THIS
If Right(docsFolder, 1) <> "\" Then docsFolder = docsFolder & "\"
On Error Resume Next
Set WordApp = GetObject(, "Word.Application")
If Err Then
Set WordApp = New Word.Application
End If
On Error GoTo 0
Set ws = ActiveSheet
For r = 2 To ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Set WordDoc = WordApp.Documents.Open(docsFolder & ws.Cells(r, "A").Value & ".docx")
With WordDoc.Content.Find
.Text = ws.Cells(r, "B").Value
.Replacement.Text = ws.Cells(r, "C").Value
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll
End With
WordDoc.Save
WordDoc.Close
Next
MsgBox "Done"
End Sub
I am getting this error while running the macroYou haven't given any details about the layout of your sheet, so I've assumed column A contains the file name of the Word document without the ".docx" extension, column B contains the old number to find and column C contains the replacement new number, all starting at row 2. Change the docsFolder path as needed.
Test the macro on a copy of your folder containing some of the Word documents.
VBA Code:Public Sub Find_and_Replace_In_Word_Docs() Dim WordApp As Word.Application Dim WordDoc As Word.Document Dim docsFolder As String Dim ws As Worksheet Dim r As Long docsFolder = "C:\path\to\docs\folder\" 'CHANGE THIS If Right(docsFolder, 1) <> "\" Then docsFolder = docsFolder & "\" On Error Resume Next Set WordApp = GetObject(, "Word.Application") If Err Then Set WordApp = New Word.Application End If On Error GoTo 0 Set ws = ActiveSheet For r = 2 To ws.Cells(ws.Rows.Count, "A").End(xlUp).Row Set WordDoc = WordApp.Documents.Open(docsFolder & ws.Cells(r, "A").Value & ".docx") With WordDoc.Content.Find .Text = ws.Cells(r, "B").Value .Replacement.Text = ws.Cells(r, "C").Value .Wrap = wdFindContinue .Execute Replace:=wdReplaceAll End With WordDoc.Save WordDoc.Close Next MsgBox "Done" End Sub
I am getting this error while running the macro
Awesome works like a charm, Thanks a lotIn the VBA editor, Tools -> References -> Microsoft Word n.00 Object Library, where n is your Word version.
The same Word object declarations are in your original code, so I thought you already had the reference.