Error accessing Word Object 2nd Time

J

John Renkar

I am using the Word Object to generate a word document. If I try to create
a second document, I get an error. If I close and reopen Access it works
fine. This leads me to believe that I am not properly releasing a resource.
Here is my code. What am I doing wrong?

After creating the document, I have checked the Task Manager and there are
no WINWORD.EXE services running. I get the following error message:

"The remote server machine does not exist or is unavailable"



Dim wrdApp As Object
Dim P1 As Object
Dim PM As Object
Dim IFile as string
Set wrdApp = CreateObject("Word.Application")

'Open Merge Document 1
IFile = "C:\REPORT_Merge_1.doc"
Set PM = wrdApp.Documents.Open(IFile)
With PM.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
Set P1 = wrdApp.ActiveDocument
PM.Close False

'Open merge document2
IFile = "C:\REPORT_Merge_2.doc"
Set PM = wrdApp.Documents.Open(IFile)
With PM.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
Selection.WholeStory
Selection.Copy
wrdApp.ActiveDocument.Close False
P1.Activate
Selection.EndKey Unit:=wdStory
Selection.PasteAndFormat (wdPasteDefault)
PM.Close False

'Save Document
IFile = "C:\NewDoc.doc"
P1.SaveAs FileName:=IFile, FileFormat:= _
wdFormatDocument, LockComments:=False, Password:="",
AddToRecentFiles:= _
True, WritePassword:="", ReadOnlyRecommended:=False,
EmbedTrueTypeFonts:= _
False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
SaveAsAOCELetter:=False

wrdApp.Visible = True
Set db = Nothing
Set PM = Nothing
Set P1 = Nothing
Set wrdApp = Nothing
 
K

Ken Snell

From what I can see, you are doing a SaveAs on the object P1, but you never
close the document after doing that. The second time through your code, you
try to save another document with the same name as the one that is still
open. You need to close P1 in your code, I believe.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top