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.

Hi,

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!

Possible cause is Word automaticly adds a blank page on load.

Is it possible that when you call the Create that is loads word into memory with the assumption of a start with blank page??

Hi
Probably it is something like that but why so many blanks? The only thing I can think of is documents that were created during earlier debugging attempts

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.