VBA macros · Printing and PDF
VBA macro to save each sheet as a separate PDF in Excel
Export every visible, non-empty sheet of a workbook to its own PDF file named after the sheet, or the whole workbook to one PDF.
Monthly statements, one sheet per client or per department, often need to go out as PDFs. File › Export handles one sheet or the whole workbook at a time, but not one file per sheet. This macro saves every visible sheet that has content as Sheet name.pdf in the workbook's folder, using each sheet's own print settings.
Option Explicit
Sub SaveEachSheetAsPdf()
Dim wb As Workbook
Dim ws As Worksheet
Dim folder As String
Dim n As Long
Set wb = ActiveWorkbook
If Len(wb.Path) = 0 Then
MsgBox "Save the workbook first; the PDFs go into its folder.", vbExclamation
Exit Sub
End If
folder = wb.Path & Application.PathSeparator
On Error GoTo Fail
For Each ws In wb.Worksheets
If ws.Visible = xlSheetVisible And _
Application.WorksheetFunction.CountA(ws.UsedRange) > 0 Then
ws.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=folder & CleanName(ws.Name) & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
n = n + 1
End If
Next ws
MsgBox n & " PDF(s) saved in " & folder, vbInformation
Exit Sub
Fail:
MsgBox "Stopped at sheet '" & ws.Name & "': " & Err.Description, vbExclamation
End Sub
Private Function CleanName(ByVal s As String) As String
' Replaces characters that are not allowed in file or sheet names
Dim ch As Variant
For Each ch In Array("\", "/", ":", "*", "?", """", "<", ">", "|", "[", "]")
s = Replace(s, ch, "_")
Next ch
CleanName = Left$(Trim$(s), 31)
End FunctionHow to use it
- Open the workbook and press
Alt+F11(Mac:Opt+F11orFn+Opt+F11) to open the VBA editor. See The Developer tab and the VBA editor if you have never used it. - Choose Insert › Module. An empty code window opens on the right.
- Paste the whole code into that window. If the module already starts with
Option Explicit, do not paste that line twice. - Go back to Excel, press
Alt+F8(Mac:Opt+F8, or Tools › Macro › Macros), pickSaveEachSheetAsPdfand click Run. - Save the file as an Excel Macro-Enabled Workbook (.xlsm). A normal .xlsx file throws the code away when you save it.
To have this macro ready in every workbook, keep it in your Personal Macro Workbook (PERSONAL.XLSB). If you do not have one yet, record any tiny macro with Store macro in: Personal Macro Workbook (see The macro recorder: record, read and clean up code), then paste this code into a module under VBAProject (PERSONAL.XLSB). The macro works on whichever workbook is active when you run it.
How it works
ExportAsFixedFormat is the VBA version of File › Export › Create PDF/XPS. Called on a worksheet, it exports just that sheet. Type:=xlTypePDF chooses PDF, Quality:=xlQualityStandard gives print quality (use xlQualityMinimum for smaller files), and IgnorePrintAreas:=False respects any print area you have set. OpenAfterPublish:=False stops thirty PDF viewer windows from opening.
Exporting an empty sheet fails with an error, so the macro checks the used range with CountA and skips sheets without content. Hidden sheets are skipped too. File names come from the sheet names, cleaned of characters that are not allowed in file names.
Each PDF uses the sheet's own page setup: orientation, margins, headers and footers, Fit to scaling and print titles. Set them once per sheet (Page Layout tab) and every export looks right. Existing PDFs with the same name are replaced.
Change it
To export the whole workbook into a single PDF instead, one line is enough:
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=ActiveWorkbook.Path & Application.PathSeparator & "Report.pdf", _
OpenAfterPublish:=TrueTo export only the sheets you have selected (click tabs with Ctrl held), use ActiveSheet.ExportAsFixedFormat: when several sheets are grouped, the active sheet's export includes all of them.
To add the date to every file name, use CleanName(ws.Name) & " " & Format(Date, "yyyy-mm-dd") & ".pdf". To force every sheet onto one page wide, set ws.PageSetup.Zoom = False, ws.PageSetup.FitToPagesWide = 1 and ws.PageSetup.FitToPagesTall = False before exporting; page setup is slow, so only do it when needed. For a single range rather than a whole sheet, see VBA macro to export a range as PDF in Excel.
What can go wrong
If the macro stops with Document not saved, the PDF is probably open in a viewer, the folder is read-only, or the file name is too long. Close the PDF and try again. Sheets with a print area that is empty also fail.
ExportAsFixedFormat can fail; install the built-in Microsoft Print to PDF printer and set it as default.Related: VBA macro to export a range as PDF in Excel, VBA macro to save each sheet as a separate workbook in Excel.