Excel VBA - Save As PDF FilesIn Excel 2010 and later, you can export a sheet, or a group of sheets, as a single PDF file. See how to manually export an Excel worksheet to PDF format, with the settings you need. Or, use the sample Excel VBA macros that automate the PDF conversion steps for you. |

To manually export the active worksheet as a PDF file, follow these steps:
The Publish as PDF or XPS window opens, where you can enter the details for the PDF file.

There are 3 Export to PDF macros in the sections below, and the next section shows the steps for using any of these pdf converter macros, in your own Excel file.
When you create PDF files, manually or with a macro, the PDF document will use the page layout settings, and print settings, from the sheets that you convert to PDF.
See the page setup tips and setting information on the Excel Printing Tips and Fixes page.
To use the Export to PDF macros in your own Excel spreadsheets, follow the steps below.
First, copy a macro's code from this page, and paste it into a regular code module in your Excel workbook.
This short video shows the steps, and there are written steps on the Copy Macro Code page.
This step is optional - you can run the code as it is, without making any changes. However, you might want to change some of the PDF export settings, to get exactly what you need in the exported file.
For notes on how to modify the code, go to the Modify Export to PDF Macros section.
When you're ready to run a macro, follow these steps:
Warning: If you have a two or more sheets selected, remember to ungroup them, before doing any more work in your Excel file.

This macro code exports the active sheet (or selected sheets) in PDF format.
See the next section, for details on how this pdf conversion macro works.
Sub PDFActiveSheet()
'www.contextures.com
'for Excel 2010 and later
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
strTime = Format(Now(), "yyyymmdd\_hhmm")
'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
'replace spaces and periods in sheet name
strName = Replace(wsA.Name, " ", "")
strName = Replace(strName, ".", "_")
'create default name for savng file
strFile = strName & "_" & strTime & ".pdf"
strPathFile = strPath & strFile
'use can enter name and
' select folder for file
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
'export to PDF if a folder was selected
If myFile <> "False" Then
wsA.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
& vbCrLf _
& myFile
End If
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
Before you run the macro in your spreadsheet, select the sheet(s) that you want to export to the PDF file.
When the macro starts, it sets variables for the active sheet, and the active workbook.
Those will be used to set the default file name and folder.
Set wbA = ActiveWorkbook Set wsA = ActiveSheet
A time stamp will be added to the default name, in the format yyyymmdd_hhmm.
In the format string shown below, a backslash is entered before the underscore, to indicate it is a literal character. Otherwise, Excel would interpret the underscore as the spacing character that is used in Excel number formatting.
Set wbA = ActiveWorkbook Set wsA = ActiveSheet strTime = Format(Now(), "yyyymmdd\_hhmm")
Next, the macro gets the default path for saving the PDF document. If the active workbook has been saved, its path is used. If the active workbook has not been saved, Excel's default save folder is used.
strPath = wbA.Path If strPath = "" Then strPath = Application.DefaultFilePath End If strPath = strPath & "\"
The name of the active sheet is cleaned up -- spaces are removed, and periods are replaced with underscores.
'replace spaces and periods in sheet name strName = Replace(wsA.Name, " ", "") strName = Replace(strName, ".", "_")
The file path, revised sheet name, and the ".pdf" extension are combined.
'create default name for savng file strFile = strName & "_" & strTime & ".pdf" strPathFile = strPath & strFile
The Save As dialog box opens, with the current folder selected, or the default save folder. The folder is filtered, to show only the PDF files that it contains.
At the top of the Save As window, the customized title is shown, "Select Folder and FileName to save"
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
The default file name is filled in, and you can overwrite it, to save the file with a different name. You can also select another folder --just browse to a different location.

Then, click the Save button, or click Cancel, if you change your mind.
If myFile <> "False" Then
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=myFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Then, if the file was created, the macro shows a confirmation message with the file path and name.
MsgBox "PDF file has been created: " _
& vbCrLf _
& myFile
Click the OK button to close the message box.

The previous macro creates a default name with a time stamp, based on the active sheet name. It prompts you to select a folder for the saved PDF file, and you can change the default name, if you prefer something different.
In the macro below, the default name is based on the values in cells A1, A2 and A3 on the active sheet.
The PDF file is automatically saved in the current folder

Sub PDFActiveSheetNoPrompt()
'www.contextures.com
'for Excel 2010 and later
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
strName = wsA.Range("A1").Value _
& " - " & wsA.Range("A2").Value _
& " - " & wsA.Range("A3").Value
'create default name for savng file
strFile = strName & ".pdf"
strPathFile = strPath & strFile
'export to PDF in current folder
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strPathFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
& vbCrLf _
& strPathFile
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
In the macro below, the default name is based on the values in cells A1, A2 and A3 on the active sheet. The PDF file is automatically saved in the current folder, with no prompts.

However, if a file with that name already exists in the current folder, a message asks if you want to overwrite the file. Click Yes or No in the message box.
NOTE: Be sure to copy the bFileExists Function too, below the main macro

Sub PDFActiveSheetNoPromptCheck()
'www.contextures.com
'for Excel 2010 and later
'checks for existing file
'prompt to overwrite or rename
'uses bFileExists Function, below
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Dim lOver As Long
On Error GoTo errHandler
Set wbA = ActiveWorkbook
Set wsA = ActiveSheet
'get active workbook folder, if saved
strPath = wbA.Path
If strPath = "" Then
strPath = Application.DefaultFilePath
End If
strPath = strPath & "\"
strName = wsA.Range("A1").Value _
& " - " & wsA.Range("A2").Value _
& " - " & wsA.Range("A3").Value
'create default name for savng file
strFile = strName & ".pdf"
strPathFile = strPath & strFile
If bFileExists(strPathFile) Then
lOver = MsgBox("Overwrite existing file?", _
vbQuestion + vbYesNo, "File Exists")
If lOver <> vbYes Then
'user can enter name and
' select folder for file
myFile = Application.GetSaveAsFilename _
(InitialFileName:=strPathFile, _
FileFilter:="PDF Files (*.pdf), *.pdf", _
Title:="Select Folder and FileName to save")
If myFile <> "False" Then
strPathFile = myFile
Else
GoTo exitHandler
End If
End If
End If
'export to PDF in current folder
wsA.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=strPathFile, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
& vbCrLf _
& strPathFile
exitHandler:
Exit Sub
errHandler:
MsgBox "Could not create PDF file"
Resume exitHandler
End Sub
'=============================
Function bFileExists(rsFullPath As String) As Boolean
bFileExists = CBool(Len(Dir$(rsFullPath)) > 0)
End Function
'=============================
In the macros on this page, the code has settings for PDF files that are created from the Microsoft Excel spreadsheets. You might prefer different settings.
The best way to see how to change the code, so that it uses your preferences, is to record an Excel macro, while you manually export an Excel sheet in PDF format. To do that, follow the steps below.
First, follow these steps to start recording a macro:

Next, while the recorder is running, export the active sheet to PDF, and choose your preferred settings.
After you click the Publish button, go to the Excel Status bar, and click the Stop Recording button.
To see the PDF code that was recorded, follow these steps:
In the recorded macro code, you can see the export settings and options that you selected.

In the Macros on this page, you can replace the sample code with your preferred settings. Just copy and paste from your recorded macro code.
For example, for the Quality setting, you could change:
If you run these macros in Excel for Office 365, you might see an error:
Or, if you try to manually export a PDF file in Excel for Office 365, you could see this error:
In one of the Excel forums on the Microsoft website, someone posted the following solution to the problem.
'====================
Quoted from Microsoft Excel Forum:
After hours of studying Process Monitor reports on two different computers and comparing them, I discovered that Microsoft Office apps look for "sRGB Color Space Profile.icm" in the wrong place and don't find it. By deleting the following Registry values, the problem goes away:
For the record, these values are all okay. There is nothing wrong with them. (The Color Management applet in the Windows Control Panel creates them.) The blame is entirely on Microsoft Office, i.e. this is a bug.
'====================
Don't miss my monthly Excel newsletter! You'll get quick tips, article links, and a bit of fun. Add your email, and click Sign Up.
Next, when you get my reply, click the Confirm button. I add this step to protect you from spam!
Macro: Update and Zip Excel Files
Excel VBA Edit Your Recorded Macro
Last updated: October 7, 2024 1:48 PM