I've created a letterwriting application which opens word, prefills a
template with data from Access, prints the word document, saves the document,
then closes it. I've cloned the code in several different routines. For some
reason the latest routine opens word and prints the letter the first time,
but in subsequent calls does not recognize the open word application
(although other routines do).
I found that if I don't save the document, it does not close without user
intervention, so I save the document then close it after it is printed. I
then set the word object to nothing. Word remains open and in all but the
last routine, the next time it is invoked, the same word session is opened.
Code:
Dim WordObj As Word.Application
Dim TemplateFile As String
dim SaveDoc as string
TemplateFile = "c:\SampleTemp.dot"
Set WordObj = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set WordObj = CreateObject("Word.Application")
End If
WordObj.Visible = True
WordObj.Documents.Add Template:=TemplateFile, NewTemplate:=False
'Fill word document with data from Access
DoEvents
WordObj.Activate
ActiveDocument.PrintOut
SaveDoc = "c:\PrintedLetter.doc" 'In some routines, the same file is
overwritter
'in others, the file is
saved with a unique name
'this routine overwrites
one file
ActiveDocument.SaveAs FileName:=SaveDoc, FileFormat:= _
wdFormatDocument, LockComments:=False, Password:="",
AddToRecentFiles:= _
True, WritePassword:="", ReadOnlyRecommended:=False,
EmbedTrueTypeFonts:= _
False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
SaveAsAOCELetter:=False
ActiveDocument.Close
Set WordObj = Nothing
Kevin K. Sullivan - 01 Sep 2005 17:23 GMT
I haven't been through all of your code, but I think the main problem is
your use of ActiveDocument. Since you always know which document (and
which Word instance) you want to use, use a specific reference. Dim an
Word.Document object just like you have a Word.Application defined.
Change
> WordObj.Documents.Add Template:=TemplateFile, NewTemplate:=False
to
Set WordDoc = WordObj.Documents.Add(Template:=TemplateFile,
NewTemplate:=False)
then change your ActiveDocument.xyz references to WordDoc.xyz and you
are assured that you are not mucking with documents that the user had
open / opens up during the process. Set WordDoc = Nothing after you
close it to be tidy.
ActiveDocument is something that Excel and Word macro recorders usually
include in their code, but I avoid them if I have specifics available.
HTH,
Kevin
> I've created a letterwriting application which opens word, prefills a
> template with data from Access, prints the word document, saves the document,
[quoted text clipped - 45 lines]
>
> Set WordObj = Nothing
cmw - 01 Sep 2005 18:45 GMT
Thanks, I'll give it a try
> I haven't been through all of your code, but I think the main problem is
> your use of ActiveDocument. Since you always know which document (and
[quoted text clipped - 71 lines]
> >
> > Set WordObj = Nothing