![]() |
Word Automation - Find/Replace
I've got an Excel macro that opens up a Word document, then uses Find/Replace
on the Word Document. Upon testing, it seems the code is able to find the text, but is not replacing it. I don't get any errors when the code compiles or runs. Following is an Excel macro I wrote as a test. When I copy this macro into my word document, remark out the lines that don't apply to Word (references to WordApp and WordDoc), and replace WordDoc with ThisDocument in the first line of my With statement, it runs fine. Any thoughts? Sub Test() Const X As String = "%LetterDate%" Const Y As String = "July 10, 2005" Dim WordApp as Object Dim WordDoc as Object Set WordApp = CreateObject ("Word.Application") WordApp.Visible = True WordApp.Documents.Open Filename:="C:\Letters\TSLetter.doc" Set WordDoc = WordApp.ActiveDocument With WordDoc.Content.Find .Text = X .Replacement.Text = Y .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = True .MatchWildCards = True .MatchSoundsLike = False .MatchAllWordForms = False .Execute Replace:=wdReplaceAll MsgBox .Found End With WordDoc.Close SaveChanges:=True WordApp.Quit Set WordApp = Nothing End Sub |
Thanks papou! It worked like a charm!
"papou" wrote: Hello When you are using the late binding method, it seems that you lose access to word constants (I have experienced this before). So I would suggest you try and replace: .Wrap = wdFindContinue with .Wrap = 1 and .Execute Replace:=wdReplaceAll with .Execute Replace:= 2 HTH Cordially Pascal "JMB" a écrit dans le message de news: ... I've got an Excel macro that opens up a Word document, then uses Find/Replace on the Word Document. Upon testing, it seems the code is able to find the text, but is not replacing it. I don't get any errors when the code compiles or runs. Following is an Excel macro I wrote as a test. When I copy this macro into my word document, remark out the lines that don't apply to Word (references to WordApp and WordDoc), and replace WordDoc with ThisDocument in the first line of my With statement, it runs fine. Any thoughts? Sub Test() Const X As String = "%LetterDate%" Const Y As String = "July 10, 2005" Dim WordApp as Object Dim WordDoc as Object Set WordApp = CreateObject ("Word.Application") WordApp.Visible = True WordApp.Documents.Open Filename:="C:\Letters\TSLetter.doc" Set WordDoc = WordApp.ActiveDocument With WordDoc.Content.Find .Text = X .Replacement.Text = Y .Forward = True .Wrap = wdFindContinue .Format = False .MatchCase = False .MatchWholeWord = True .MatchWildCards = True .MatchSoundsLike = False .MatchAllWordForms = False .Execute Replace:=wdReplaceAll MsgBox .Found End With WordDoc.Close SaveChanges:=True WordApp.Quit Set WordApp = Nothing End Sub |
All times are GMT +1. The time now is 02:53 PM. |
Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com