I am trying to make an excel document that I can paste a list of words to search and replace into. I want to use the excel document to search and replace these words in a word document.
I am having issues getting the code to function.
Sub SearchReplace()
Dim WordDoc As Object, N As Variant, i As Integer, j As Integer
i = Range("C2").Value 'pulls length of list from an excel function located in cell C2
N = Range("B4:C" & CStr(i + 3)).Value
Set WordDoc = CreateObject(Class:="Word.Application")
WordDoc.Visible = True
WordDoc.Documents.Open Filename:="C:\WordTest.docm"
WordDoc.Activate
With WordDoc.ActiveDocument
For j = 1 To i
With .Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.MatchWildcards = False
.Wrap = wdFindContinue
.Text = N(1, j)
.Replacement.Text = N(2, j)
.Execute
End With
End With
Next j
End With
WordDoc.Quit
Set WordDoc = Nothing
End Sub
I corrected the code based on the recommendations, and I no longer get any errors. However the code does not appear to find and replace anything in the specified word document. I tried to simplify the code to check the find & replace portion by typing in a specific word "text" and a specific word "replace" to find and replace in a word document, which contains the word "text". This still result in no change. I removed the line that closed the document in case the issue was the document was not being saved after being updated, but that also was not successful, so I added WordDoc.Quit back into the code.
Sub SearchReplace()
Dim WordDoc As Object, N As Variant, i As Integer, j As Integer
i = Range("C2").Value 'pulls length of list from an excel function
located in cell C2
N = Range("B4:C" & CStr(i + 3)).Value
Set WordDoc = CreateObject(Class:="Word.Application")
WordDoc.Visible = True
WordDoc.Documents.Open Filename:="C:\WordTest.docm"
WordDoc.Documents("WordTest.docm").Activate
With WordDoc.ActiveDocument
For j = 1 To i
With .Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.MatchWildcards = False
.Wrap = 1
.Text = "text" 'N(j, 1)
.Replacement.Text = "replace" 'N(j, 2)
.Execute 2
End With
End With
Next j
End With
WordDoc.Quit
Set WordDoc = Nothing
End Sub
wdFindContinue
is. You'll need to either add the reference, or define that constant. And useOption Explicit
so you always know about this type of problem. – Tim Williams