Visual Basic for Applications (VBA) is the programming language used with Microsoft Office to make the applications perform dynamic tasks, one of which is opening and printing out PDF files. To perform this task, you need a basic understanding of the VBA language and the VBA editor that comes installed with every version of the Microsoft Office programs. This code can be used for any of the Microsoft Office applications.
Open the VBA editor in the Microsoft Office application that you want the code to be entered into. Click on \"File\" > \"Tools\" > \"Macros\" > \"Visual Basic Editor\" in an application of Microsoft Office 2003 or earlier. Click on \"Developer tab\" > \"Visual Basic\" in the 2007 edition of Microsoft Office.
Click anywhere in the code window where you want to insert the code.
Add the code to open the PDF file. You code should look something like this:
Video of the Day
Sub OpenPDF() Dim strPDFFileName As String 'Edit to add the full filename to the PDF file that you want to open strPDFFileName = \"C:\examplefile.pdf\" 'This next function checks to see if the file isn't already open If Not FileLocked(strPDFFileName) Then 'If it returns False, then continue opening the PDF file Documents.Open strPDFFileName) End If End Sub
Copy and paste this code into your code window. The only part of the code that you will need to change is the full path to the PDF file you want to open. So, replace the \"C:\examplefile.pdf\" with your own file path and name.
Add the code to print the PDF file. The printing code is:
Sub PrintPDF (strPDFFileName as string) Dim sAdobeReader as String 'This is the full path to the Adobe Reader or Acrobat application on your computer sAdobeReader = \"C:\Program Files\Adobe\Acrobat 6.0\Reader\AcroRd32.exe\" RetVal = Shell(sAdobeReader & \"/P\" & Chr(34) & sStrPDFFileName & Chr(34), 0) End Sub
The only part of this code that needs to be changed is the full path to the Adobe Reader, Acrobat or any PDF reader on your computer.
Use a trigger to call the functions. This is how the code will know when to execute. Use whatever trigger you want; a form, button, checkbox or other form item. For example, use the \"Click\" declaration of a button. When the button is clicked, the PDF document will open and then print. The code looks like this:
Sub CommandButton_Click() 'Call the open function first so that the PDF can open before printing Call OpenPDF 'Now call the print function so that the PDF can be printed Call PrintPDF End Sub
Just copy the middle portion of the above code (between the Sub and End Sub) into the form item and trigger you decide to use.