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")
.Visible = True
objDoc = objWord.Documents.Add(Template:=TemplatePath)
.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")
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
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.
I think I did solve it although it's kind of a cheat, I put my loop where I close the documents down after I populate the bookmarks and it appears to work. It still does not explain the multiple documents opening though!