I am hoping someone can help me with what seems to be a relatively simple problem. I am attempting to automate a Word 2007 document using Access 2007. The code I am posting works perfectly to find and replace placeholder text in the Word document body as well as in the footer.
However, the code will only run properly one time. When run a second time it hangs on the Set rng = ActiveDocument.StoryRanges(wdPrimaryFooterStory) line of code and brings up Error 462 indicating that the remote server is unavailable. The error will clear itself if I just close and reopen the Access form from which the code is launched. Then it will again run perfectly one time.
Also, if I remove the portion of the code that pertains to updating the text in the footer, it runs perfectly without generating the error.
It seems to me that my code is not able to close out the Word object completely. By closing the Access form ( or closing the Access application) the "remnant" of this Word object is cleared. However, I need the code to be able to process multiple Word documents in succession so even closing the Access form each time would be tedious and truly pathetic.
Anyway, it seems to me that the ActiveDocument method seems to have a memory that exists even with all of the .Quit and Set X = Nothing statements that I have in the code.
The code is a little simplistic right now but until I get the Error issue solved I haven't been concerned about making the routine a bit more sophisticated.
Thanks. Sorry I am am not a great VB programmer so please try to be gentle.
Private Sub Command1_Click()
Dim appWord As Word.Application
Dim doc As Word.Document
Dim rng As Word.Range
Dim strDoc As String
strDoc = "C:\WVLCStudio\LASIKInformedConsentTemplate.dotx"
Set appWord = New Word.Application
.WindowState = wdWindowStateNormal
.Visible = True
Set doc = .Documents.Add(strDoc)
.MatchWholeWord = True
.Execute FindText:="%PatientName%", ReplaceWith:="Hello World", _
.Forward = True
.Wrap = wdFindContinue
Set rng = ActiveDocument.StoryRanges(wdPrimaryFooterStory)
.Find.Text = "%PatientName%"
.Find.Replacement.Text = "John Smith"
Set appWord = Nothing
Set doc = Nothing