Reputation: 433
From within Excel, I need to open a Word document (I succeeded at this) and then perform (programatically) a Find/Replace inside that document (No success at this).
The reason to use an Excel macro is that the replacement text is taken from some Excel cells.
Sub Word_find_replace_attempt_from_Excel()
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
Set WordDoc = WordApp.Documents.Open("C:\Test.doc") 'it exists already
With WordDoc
Find.Execute _
FindText:="a", _
ReplaceWith:="b", _
Replace:=wdReplaceAll
End with
End Sub
Upvotes: 0
Views: 1348
Reputation:
You don't need to set a referenece to MS Word, but make sure that declare consts for any MS Word Enumerations that you use.
Sub Word_find_replace_attempt_from_Excel()
Const wdReplaceAll = 2
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
Set WordDoc = WordApp.Documents.Open("C:\Test.doc")
With WordDoc.Content.Find
.Execute FindText:="a", ReplaceWith:="b", _
Format:=True, Replace:=wdReplaceAll, Forward:=True
End With
End Sub
Upvotes: 1