Link to home
Start Free TrialLog in
Avatar of Jeff McClellan
Jeff McClellanFlag for United States of America

asked on

How to automatically save & name a document as a PDF when closing.

I have a word template that generates a contract using data from a non-microsoft windows app.

I want to use a VBA script that will save the file as a PDF (using Acrobat or CutePDF Writer) to a path, and with a filename that will be determined from merge fields in the merged document.
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

That would normally be done by putting some code in the Document_Close event in the ThisDocument module, but there are a number of problems.

Firstly, in which Template project would it go? A mail merge Main document is not technically a template in the Word sense. Therefore result documents do not reference it, so the event wouldn't be fired.

If the code were in the main document's own template (probably the Normal template), then the code would have to identify the document as one that has to be processed in this way, and not one of the many othere documents that you might want to open or create and close.

Another problem is that a mailmerge execution  produces an output for each record processed. If it is another documents, each record's result is one section of the document, so the pdf would have the name of one of the records only.

Finally, there could be a problem in location the text that replaces the mailmerge field in the main document.

However here is a simple example

Private Sub Document_Close()
    If Trim$(ActiveDocument.words(1)) = "My Title" Then
        ActiveDocument.SaveAs "C:\MyFolder\" & Trim$(ActiveDocument.words(2)) & ".pdf", wdFormatPDF
    End If
    ActiveDocument.Close
End Sub

Open in new window

Avatar of Jeff McClellan

ASKER

Thanks for your thoughtful reply.

The "template" is currently saved as a .doc, not a .dot - if that matters.

Each contract is generated independently from a single database record, never multiple contracts in a batch.

I'll give the code a try and see what happens.
If I put this into the "template's" ThisDocument, it breaks at ActiveDocument.Close

Is there a way to pass this script on to the product of the templates output so it will only run then?
Do you men that there is an error? If so, what is the error message?
ASKER CERTIFIED SOLUTION
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mike McCracken
Mike McCracken

This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.