How to save Excel as PDF with VBA (10 examples) (2024)

Since Excel 2010, it has been possible to save Excel as PDF.The PDF format was then and continues to be, one of the most common file formats for distributing documents.

The code examples below provide the VBA macros to automate the creation of PDFs from Excel using the ExportAsFixedFormat method. This means you do not require a PDF printer installed, as Excel can print directly to a PDF document.

Table of Contents
  • Saving Excel workbooks, sheets, charts, and ranges as PDF
    • Save active sheet as PDF
    • Save active workbook as PDF
    • Save selection as PDF
    • Save a range as PDF
    • Save a chart as PDF
    • Adapting the code to your scenario
    • Notes for saving PDF documents
  • Selecting specific worksheets before saving as PDF
  • Looping and saving as separate PDFs
    • Loop through sheets
    • Loop through selected sheets
    • Loop through charts
  • Other PDF print options
    • VBA Save to PDF Example using all the options
  • Other fixed formats available (xlTypeXPS)
  • Conclusion

The example codes can be used independently or as part of a larger automation process. For example, check out this post to see an example of how to loop through a list and print a PDF for each item: Create multiple PDFs based on a list

Rather than going from Excel to PDF, you might want to go the other way; from PDF to Excel.Check out these posts for possible solutions for that scenario:

Download the example file:Join the free Insiders Program and gain access to the example file used for this post.

File name: 0019 Save Excel as PDF with VBA.zip

Get access

Saving Excel workbooks, sheets, charts, and ranges as PDF

This section contains the base code to save Excel as PDF from different objects (workbooks, worksheets, ranges, and charts).From a VBA perspective, it is the ExportAsFilxedFormat method combined with the Type property set to xlTypePDF that creates a PDF.

Save active sheet as PDF

The following code saves the selected sheets as a single PDF.

Sub SaveActiveSheetsAsPDF()'Create and assign variablesDim saveLocation As StringsaveLocation = "C:\Users\marks\OneDrive\Documents\myPDFFile.pdf"'Save Active Sheet(s) as PDFActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=saveLocationEnd Sub

Save active workbook as PDF

Use the following macro to save all the visible sheets from a workbook.

Sub SaveActiveWorkbookAsPDF()'Create and assign variablesDim saveLocation As StringsaveLocation = "C:\Users\marks\OneDrive\Documents\myPDFFile.pdf"'Save active workbook as PDFActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=saveLocationEnd Sub

Save selection as PDF

Sometimes, we only want to save a small part of a worksheet to a PDF.The following code prints only the selected cells.

Sub SaveSelectionAsPDF()'Create and assign variablesDim saveLocation As StringsaveLocation = "C:\Users\marks\OneDrive\Documents\myPDFFile.pdf"'Save selection as PDFSelection.ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=saveLocationEnd Sub

Save a range as PDF

The macro below saves a specified range as a PDF.

Sub SaveRangeAsPDF()'Create and assign variablesDim saveLocation As StringDim ws as WorksheetDim rng As RangesaveLocation = "C:\Users\marks\OneDrive\Documents\myPDFFile.pdf"Set ws = Sheets("Sheet1")Set rng = ws.Range("A1:H20")'Save a range as PDFrng.ExportAsFixedFormat Type:=xlTypePDF, _Filename:=saveLocationEnd Sub

Save a chart as PDF

The VBA code below saves a specified chart as a PDF.

Sub SaveChartAsPDF()'Create and assign variablesDim saveLocation As StringDim ws As WorksheetDim cht As ChartsaveLocation = "C:\Users\marks\OneDrive\Documents\myPDFFile.pdf"Set ws = Sheets("Sheet1")Set cht = ws.ChartObjects("Chart 1").Chart'Save a chart as PDFcht.ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=saveLocationEnd Sub

Rather than naming a specific chart, the macro could run based on the active chart. Change this:

Set cht = ws.ChartObjects("Chart 1").Chart

To this:

Set cht = ActiveChart

Adapting the code to your scenario

To adapt the code examples to your specific needs, you should adjust certain lines of code.

Change the save location

To save the file in the correct location, change this list of code:

saveLocation = "C:\Users\marks\OneDrive\Documents\myPDFFile.pdf"

If you would prefer the save location to be included in a cell, change the code to reference the sheet and cell containing the file path.

saveLocation = Sheets("Sheet1").Range("B2").Value

Change the worksheet

In this line of code, change the text “Sheet1” to the sheet name in your workbook.

Set ws = Sheets("Sheet1")

Change the range

The following line of codes references the range to be printed to PDF.

Set rng = ws.Range("A1:H20")

Change the chart

To print a chart to PDF, change the chart’s name in the following line of code.

Set cht = ws.ChartObjects("Chart 1").Chart

If you are unsure of the chart name, it is shown in the Name box when the chart is selected.

Notes for saving PDF documents

While the Filename property is optional, it is important to know where the file is saved.

  • If the Filename property is not provided, the PDF saves in your default folder location using the Excel workbook’s name with the .pdf file extension.
  • Where a file name is provided, but not a file path, the document saves in your default folder location with the name provided.
  • When the .pdf file extension is not provided, the suffix is added automatically.
  • If a PDF exists in the specified save location, the existing file is overwritten. Therefore, it may be necessary to include file handling procedures to prevent overwriting existing documents and handling errors.
  • To save as an XPS document format, change xlTypePDF for xlTypeXPS.

Selecting specific worksheets before saving as PDF

If more than one worksheet is active, the PDF created includes all the active sheets.The following code selects multiple worksheets from an array before saving the PDF.

Sub SelectSheetsAndSaveAsPDF()'Create and assign variablesDim saveLocation As StringDim sheetArray As VariantsaveLocation = "C:\Users\marks\OneDrive\Documents\myPDFFile.pdf"sheetArray = Array("Sheet1", "Sheet2")'Select specific sheets from workbook, the save all as PDFSheets(sheetArray).SelectActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=saveLocationEnd Sub

In the code above, an array is used to select the specific sheets. Alternatively, the Split array function with a text string could provide a more dynamic solution. This method is covered here: VBA Arrays.

Looping and saving as separate PDFs

To save multiple PDFs quickly, we can use VBA to loop through sheets or charts and save each individually.

Loop through sheets

The following macro loops through each worksheet in the active workbook and saves each as its own PDF. Each PDF is saved in the same folder as the workbook, where each PDF’s name is based on the worksheet’s name.

Sub LoopSheetsSaveAsPDF()'Create variablesDim ws As Worksheet'Loop through all worksheets and save as individual PDF in same folder'as the Excel fileFor Each ws In ActiveWorkbook.Worksheets ws.ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=ThisWorkbook.Path & "/" & ws.Name & ".pdf"NextEnd Sub

Loop through selected sheets

The following macro loops through only the selected worksheets in the active workbook and saves each as its own PDF.

Sub LoopSelectedSheetsSaveAsPDF()'Create variablesDim ws As WorksheetDim sheetArray As Variant'Capture the selected sheetsSet sheetArray = ActiveWindow.SelectedSheets'Loop through each selected worksheetFor Each ws In sheetArray ws.Select ws.ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=ThisWorkbook.Path & "/" & ws.Name & ".pdf"Next ws'Reselect the selected sheetssheetArray.SelectEnd Sub

Loop through charts

The following code loops through each chart on the active sheet and saves each as a separate PDF.

Sub LoopChartsSaveAsPDF()'Create and assign variablesDim chtObj As ChartObjectDim ws As WorksheetSet ws = ActiveSheet'Loop through all charts and save as individual PDF in same folder'as the Excel fileFor Each chtObj In ws.ChartObjects chtObj.Chart.ExportAsFixedFormat Type:=xlTypePDF, _ Filename:=ThisWorkbook.Path & "/" & chtObj.Name & ".pdf"Next chtObjEnd Sub

Other PDF print options

When using ExportAsFixedFormat, there are other optional settings available:

'Open the document after it is saved - options are True /FalseOpenAfterPublish:=False'Include the Excel document properties into the PDF - options are True /FalseIncludeDocProperties:=True'Does the created PDF adhere to the Print Areas already set in the 'worksheet - options are True /FalseIgnorePrintAreas:=False'Set the output quality of the created document - options are 'xlQualityMinimum / xlQualityStandardQuality:=xlQualityStandard'The page to start printing. If excluded, will start from the first pageFrom:=1'The page to print to. If excluded, will go to the last pageTo:=2

VBA Save to PDF Example using all the options

The code below demonstrates how to use all the options within a single macro.These options can be flexed to meet your requirements.

Sub SaveAsPDFOptions()Dim saveLocation As StringsaveLocation = "C:\Users\marks\Documents\myPDFFile.pdf"'Example using all the optionsActiveSheet.ExportAsFixedFormat _ Type:=xlTypePDF, _ Filename:=saveLocation, _ OpenAfterPublish:=False, _ IncludeDocProperties:=True, _ IgnorePrintAreas:=False, _ Quality:=xlQualityStandard, _ From:=1, To:=2End Sub

Other fixed formats available (xlTypeXPS)

The Type property can also create XPS documents when it is set to xlTypeXPS rather than xlTypePDF.XPS is Microsoft’s fixed file format; it is similar to PDF but based on the XML language. It is rarely used in the real world but is an option if required.

Conclusion

Learning how to save Excel as PDF is a good time investment.Each of these code snippets on its own is useful.However, the code examples above can be used in other automation to create even more time-saving.

Related posts:

  • Excel – Create multiple PDFs based on a list
  • Loop through selected sheets with VBA
  • How to loop through each item in Data Validation list with VBA

What next?

Discover how you can automate your work with our Excel courses and tools.

How to save Excel as PDF with VBA (10 examples) (1)

Excel Academy
The complete program for saving time by automating Excel.

Find out more

How to save Excel as PDF with VBA (10 examples) (2)

Excel Automation Secrets
Discover the 7-step framework for automating Excel.

Find out more

How to save Excel as PDF with VBA (10 examples) (3)

Office Scripts: Automate Excel Everywhere
Start using Office Scripts and Power Automate to automate Excel in new ways.

Find out more

How to save Excel as PDF with VBA (10 examples) (2024)

FAQs

How to save Excel file as PDF using VBA? ›

1. Save Active Excel Sheets as PDF With VBA
  1. Open the Excel Workbook with MS Excel.
  2. Ensure you are viewing the sheet you want to save as a PDF.
  3. Press "Alt + F11" on your keyboard to open VBE (Visual Basic Editor.)
  4. Find your workbook name in the "Project-VBAProject" panel. ...
  5. Click "Insert" > "Module."
  6. Paste this code:

How to automatically save Excel as PDF? ›

Export Excel as PDF for Windows
  1. In your workbook, head to File > Save As, or File > Save a copy.
  2. Click “Browse”.
  3. In the “Save as type” dropdown, select “PDF”.
  4. Press “Options…”. ...
  5. Click “o*k” to close the “Options…” window.
  6. Click “Save” to save the new PDF version.
Mar 13, 2024

How do I save an Excel file with VBA code? ›

To save an Excel workbook using VBA, you need to use the SAVE method to write a macro. And in that macro, you need to specify the workbook that you want to save and then use the SAVE method. When you run this code, it works like the keyboard shortcut (Control + S). Specify the workbook hat you want to save.

How to convert Excel file into PDF without losing formatting? ›

Common formatting issues when converting Excel to PDF.
  1. Open the File menu in the top left corner.
  2. Click Export.
  3. In the panel that appears, click Create PDF/XPS Document.
  4. Optimize the file for Standard or Minimum.
  5. Click Options and adjust settings, including the area to publish.
  6. Click OK.
  7. Name the file and click Publish.

How to convert an entire Excel workbook to PDF? ›

Re: how to convert an excel workbook into pdf in which internal links still work?
  1. Open your Excel workbook.
  2. Click on "File" in the top-left corner of the screen.
  3. Select "Save As".
  4. Choose "PDF (*. ...
  5. Click on the "Options" button.
  6. In the "Publish Options" section, select "Minimum size (publishing online)".
  7. Click on "OK".

How do you enable Save As as PDF in Excel? ›

Select Save .
  1. Select the File tab.
  2. Select Save As . ...
  3. In the File Name box, enter a name for the file, if you haven't already.
  4. In the Save as type list, select PDF (*.pdf) . ...
  5. Select Options to set the page to be printed, to choose whether markup should be printed, and to select output options. ...
  6. Select Save .

How do I auto populate an Excel File to PDF? ›

How Do I Autofill PDF Forms from Excel?
  1. Open the My Docs tab. ...
  2. Click the “Fill in bulk” option in the right sidebar.
  3. Next, you will see a pop-up window with detailed instructions. ...
  4. You will see the table that includes all cells from the documents in multiple rows.
  5. Some fields can be added in the editor.

What format is save as File in VBA workbook? ›

The Save As feature lets you specify a new file name when saving. The original workbook remains unchanged when you use the Save As function in Excel VBA. Save As also allows you to choose a different file format for the saved workbook. Excel offers various file formats like XLSX, XLSM, CSV, or PDF.

How do I save and run VBA code? ›

Save your workbook as "Excel macro-enabled workbook". Press Crl + S, then click the "No" button in the "The following features cannot be saved in macro-free workbook" warning dialog. The "Save as" dialog will open. Choose "Excel macro-enabled workbook" from the "Save as type" drop-down list and click the Save button.

How do I export VBA from Excel? ›

In the Project window in the VBA editor, click the module you want to export. Click File, then click Export File. Navigate to the folder where you want to store the Visual Basic Module and click Save.

How to bulk convert Excel to PDF? ›

To save multiple sheets in an Excel workbook as a PDF:
  1. Open your Excel workbook.
  2. Hold down the 'Ctrl' key on your keyboard.
  3. Click on the tabs of the sheets you want to save as a PDF. ...
  4. Go to 'File' in the top left corner.
  5. Choose 'Save As. ...
  6. Select the location where you want to save the file.

How to print Excel workbook to PDF? ›

To print a spreadsheet to PDF and send it to email in Excel 365, you can follow these steps:
  1. Click on "File" in the top left corner of the Excel window.
  2. Click on "Export" and then select "download as PDF".
  3. Download location where you want to save the PDF file and give it a name.
Dec 29, 2023

How to create a PDF file from Excel? ›

Re: how to convert an excel workbook into pdf in which internal links still work?
  1. Open your Excel workbook.
  2. Click on "File" in the top-left corner of the screen.
  3. Select "Save As".
  4. Choose "PDF (*. ...
  5. Click on the "Options" button.
  6. In the "Publish Options" section, select "Minimum size (publishing online)".
  7. Click on "OK".

How do I convert Excel macro to PDF with password? ›

Start a macro recorder, go to: File / Save as. Select “Save as Type” and pick “PDF”. You will see an “Options…” button appear. Click that and check the box “Encrypt the document with a password”.

How to generate a report in Excel using VBA PDF? ›

VBA routines for publishing reports:
  1. Delete completely blank rows in the selection.
  2. Sort selected sheets alphabetically.
  3. Set selected sheets to “Very Hidden”
  4. Export each sheet into a separate PDF Report.
  5. Export all charts to a PPT workbook.

How to save an Excel file as a PDF in VB net? ›

Convert worksheet to PDF in C#, VB.NET
  1. Step 1: Initialize a new instance of Workbook class and load the sample Excel file.
  2. Step 2: Get its first worksheet.
  3. Step 3: Convert the selected worksheet to PDF and save to file.
  4. Step 4: Launch the file.
  5. Effective screenshot:
  6. Full codes:

Top Articles
Latest Posts
Article information

Author: Madonna Wisozk

Last Updated:

Views: 6288

Rating: 4.8 / 5 (48 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Madonna Wisozk

Birthday: 2001-02-23

Address: 656 Gerhold Summit, Sidneyberg, FL 78179-2512

Phone: +6742282696652

Job: Customer Banking Liaison

Hobby: Flower arranging, Yo-yoing, Tai chi, Rowing, Macrame, Urban exploration, Knife making

Introduction: My name is Madonna Wisozk, I am a attractive, healthy, thoughtful, faithful, open, vivacious, zany person who loves writing and wants to share my knowledge and understanding with you.