VBA code in Access report to export a copy of itself to a PDF file


I am using Access  (Office 365) 64 bit

I have created a report in access.  I would like to have some code on the Report Open event that would export a PDF version of itself to a predetermined folder.  I expect that the formatting will be preserved in the export to PDF.

The name of the report is "Qry Temp".

I would appreciate your help
Who is Participating?
Sorry in VBA it is:
Const reportCode As String = "Qry Temp"
Const outputToPathFile As String = "C:\YourReport.pdf"

Private Sub Report_Open(Cancel As Integer)
  DoCmd.OutputTo acOutputReport, reportCode, acFormatPDF, outputToPathFile, False, , , acExportQualityPrint
End Sub

Open in new window

In VB.Net
Imports Microsoft.Office.Interop

Dim accessApp As Access.Application = New Access.ApplicationClass
Dim reportCode As String = "Qry Temp"
Dim outputToPathFile As String = "C:\YourReport.pdf"

' Open Instance of MS Access Application
accessApp.OpenCurrentDatabase("C:\YourMsAccessDatabase.accdb", False)

' Run Report
accessApp.DoCmd.OpenReport(reportCode, Access.AcView.acViewPreview)
accessApp.DoCmd.OutputTo(Access.AcOutputObjectType.acOutputReport, reportCode, Access.Constants.acFormatPDF, outputToPathFile, False, , , Access.AcExportQuality.acExportQualityPrint)
accessApp.DoCmd.Close(Access.AcObjectType.acReport, reportCode, Access.AcCloseSave.acSaveNo)
' Clean up
accessApp = Nothing

Open in new window

peispudAuthor Commented:
Thank you for the code.    I was hoping for Access VBA  though
peispudAuthor Commented:
I have your code under a control (button)   in the report that I am trying to export.
I have also closed the report and tried to execute the code from another form.

In each case, I receive the following error

run-time error '2501'
The OutputTo action was cancelled.
peispudAuthor Commented:
Your code was correct.

I was able to fix it by changing the     Const outputToPathFile As String = "C:\YourReport.pdf" to another location on my hard drive.  Must have something to do with privileges.

Thank you!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.