Hi,
Getting some strange behaviour when using Interop to create a Word document from a template. I'm using word to generate a nicely formatted and printable Receipt from Sage 200 based on a Word Template. The code should open Word then create a new document based on the template I have created with bookmarks to populate with the receipt data.
The issue is that instead of seeing a single document, I see about 5-6 documents appearing! One of the documents is based on the template I want and the rest are all blank. Also, the document based on the template is sometimes the Active document but sometime it isn't. I only want the single document to be visible. Anyone out there any ideas?
Here is my code:
Sub ShowReceipt (byRef TemplatePath as string)
dim objWord, objDoc as object
'Late bind to avoid version issues
objWord = CreateObject("Word.Application")
With objWord
.Visible = True
End With
objDoc = objWord.Documents.Add(Template:=TemplatePath)
With objDoc
.Bookmarks("CustomerNAME").Range.Text = Trim(Customer.Name)
.Bookmarks("CustomerADDRESS").Range.Text = CustomerAddress
.Bookmarks("CustomerCONTACT").Range.Text = CustomerContactName
.Bookmarks("AMOUNT").Range.Text = ChequeValue
.Bookmarks("RECEIPTDATE").Range.Text = FormatDateTime(ReceiptDate, DateFormat.LongDate)
.Bookmarks("CURRENTBALANCE").Range.Text = Format(NewBalance, "#.00")
End With
End Sub
I did try adding the following code after adding the objDoc:
for each Item as Object in objWord.Documents
if Not Item.Equals(objDoc) then
Item.Close(SaveChanges:=False)
End if
next
and while stepping through in debug mode, I could see documents being closed and the objDoc being "skipped" but there were still other documents open at the end of the routine.