How to Print to PDF Using VBA (With Example)


You can use the following syntax in VBA to print the currently active Excel sheet to a PDF:

Sub PrintToPDF()

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
                                Filename:="my_data.pdf", _
                                Quality:=xlQualityStandard, _
                                IncludeDocProperties:=False, _
                                IgnorePrintAreas:=False, _
                                OpenAfterPublish:=True

End Sub

This particular macro will print the currently active Excel sheet to a PDF called my_data.pdf and it will be saved in the current folder.

Note #1: You can also include a full file path in the Filename argument to save the PDF to a specific folder.

Note #2: The line OpenAfterPublish:= True tells VBA to open the PDF as soon as it is exported. You can leave out this argument if you don’t want the PDF to be opened after exporting.

Note #3: The only required argument in the ExportAsFixedFormat method is Type, which must be set to xlTypePDF to print the sheet to a PDF format.

The following example shows how to use this macro in practice.

Example: Export Excel Sheet to PDF Using VBA

Suppose we have the following Excel sheet that contains information about various basketball players:

Now suppose that we would like to export this sheet to a PDF called my_data.pdf.

We can create the following macro to do so:

Sub PrintToPDF()

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
                                Filename:="my_data.pdf", _
                                Quality:=xlQualityStandard, _
                                IncludeDocProperties:=False, _
                                IgnorePrintAreas:=False, _
                                OpenAfterPublish:=True

End Sub

When we run this macro, the Excel sheet is exported to a PDF and then the PDF is automatically opened:

Note that the exact formatting of the cells with the borders and the fill color is included in the PDF.

Note: You can find the complete documentation for the ExportAsFixedFormat method in VBA here.

Additional Resources

The following tutorials explain how to perform other common tasks in VBA:

VBA: How to Create Folders
VBA: How to Delete Folders
VBA: How to Delete Files

One Reply to “How to Print to PDF Using VBA (With Example)”

Leave a Reply

Your email address will not be published. Required fields are marked *