ACCESS EXPERTS

FOR HELP WITH YOUR ACCESS DATABASES, INCLUDING SQL SERVER, WE ARE JUST ONE CLICK AWAY...


Tuesday, July 13, 2010

How to create PDFs in Word using Access VBA

Office 2007 will allow you to easily create PDFs from any Word Document using the output menu on the Office button, (Access does too with Reports), but recently I had to create a procedure for a client that wanted to convert Word docs to PDF, email them and do it all from Access.

Note: To make this code work, you will need to add a reference to Word 2007 to your Access database.

Here is the code:

Private Sub CreatePDF(strSourceFile As String, strDestFile As String)

Dim objWord As Word.Application

Dim objWordDoc As Word.Document

On Error GoTo ErrorHandler

Set objWord = CreateObject("Word.Application")

objWord.Visible = True

Set objWordDoc = objWord.Documents.Open(strSourceFile)

If Not objWord Is Nothing Then

objWordDoc.ExportAsFixedFormat strDestFile, wdExportFormatPDF, False, wdExportOptimizeForPrint, wdExportAllDocument

End If

ExitProcedure:

objWordDoc.Close False

objWord.Quit

Set objWordDoc = Nothing

Set objWord = Nothing

Exit Sub

ErrorHandler:

MsgBox Err.Description, vbInformation, "Error Creating PDF"

End Sub

Note how I display Word at the begining of the process, not doing so may leave Word "hanging" in memory if your code comes back with an error.

No comments:

Post a Comment