Sub topic 10
Exporting a Sheet, Selection, or Workbook to PDF
This chapter assumes you can already set a print area, choose orientation and scaling, repeat title rows, and add footers. Those settings from earlier chapters decide what the PDF looks like. Exporting adds one more decision: which part of the file goes into the PDF, and where the PDF is saved.
Why PDF export uses your print settings
A PDF export in Excel is a print job sent to a virtual printer. Excel paginates the sheet exactly as it would for paper. It applies the print area, orientation, paper size, margins, scaling, page breaks, print titles, headers, and footers. It then writes the result to a file instead of a printer.
Two consequences follow:
- If the print preview looks wrong, the PDF will look wrong. Check the preview first.
- The page layout is stored per sheet. Each worksheet can have its own orientation, scaling, and print area, so a workbook export can mix portrait and landscape pages.
The paper size matters too. Excel lays out pages using the paper size and the printer driver's margin limits. A layout built for Letter can paginate differently when exported on a machine whose default is A4. Set the paper size explicitly in Page Setup so the PDF does not depend on the machine.
Three ways to export
Excel offers several routes to a PDF. They differ in control and in what they include.
| Method | Where | Best for |
|---|---|---|
| Export > Create PDF/XPS | File > Export | Choosing a scope and options in a dialog |
| Save As, type PDF | File > Save As (or Save a Copy) | Quick export with the file dialog you already know |
| Print to PDF | File > Print, printer "Microsoft Print to PDF" | Machines where the Export route is unavailable |
The first two use Excel's own PDF writer. They offer an Options button. The Print to PDF printer is a Windows feature. It ignores the Options dialog described below and produces larger files, with no document properties or accessibility tags.
Export through the ribbon
- Open File > Export > Create PDF/XPS Document, then choose Create PDF/XPS.
- Choose a folder and file name in the Publish dialog.
- Set "Optimize for" to Standard (publishing online and printing) or Minimum size (publishing online).
- Select Options to choose what to publish.
- Select Publish.
The Options button is where scope is decided.
Choosing the scope
The Options dialog has a Publish what section with these choices:
| Option | What it exports |
|---|---|
| Selection | Only the cells you selected before opening the dialog |
| Active sheet(s) | The current sheet, or every sheet in a group if you grouped several |
| Entire workbook | Every visible sheet, each paginated by its own page setup |
| Table | A selected Excel table only |
The Selection option is chosen automatically when you have a range selected. This catches many people out. If you select a few cells by accident and then export, you get a PDF of those cells and nothing else. Click a single cell before exporting if you want the whole sheet.
Selection and the print area
A selection overrides the sheet's print area for that export. A single-cell selection does not count as a selection, so the print area applies. The "Ignore print areas" check box in Options tells Excel to export the whole used range of each sheet and skip the defined print areas. Leave it cleared in normal use.
Multiple sheets and sheet groups
Active sheet(s) exports every sheet in a group. To export two of five sheets, hold Ctrl and click their tabs to group them, then export. Ungroup afterward by clicking a tab outside the group. Editing a grouped sheet changes all sheets in the group, so avoid typing while grouped.
Entire workbook skips hidden sheets. Hide the sheets you want excluded, such as raw data or calculations, and the workbook export leaves them out. Very hidden sheets are also skipped.
One PDF or many
Excel produces one PDF per export, with pages in tab order. If you need one PDF per sheet, export each sheet separately or use a macro (shown later in this chapter).
Export options that affect the file
The Options dialog contains several more settings.
- Page range. Choose Page(s) and enter From and To values to export only part of the paginated output. The numbers refer to pages in the printed order, not to rows.
- Include non-printing information. Document properties and, for accessibility, document structure tags. Turn on "Document structure tags for accessibility" when the PDF goes to people using screen readers. It increases file size slightly.
- Create bookmarks using. Excel can add PDF bookmarks, one per sheet or per named range. Sheet bookmarks help readers jump around a multi-sheet PDF.
- ISO 19005-1 compliant (PDF/A). Produces an archival format. Use it when a records policy requires PDF/A. It disables some features, such as embedding fonts that cannot be embedded.
- Optimize for. Standard keeps print-quality images. Minimum size lowers image resolution to reduce file size. Use Minimum size for email and Standard for anything that will be printed later.
Pre-flight checklist
Run through this list before each export. It catches most problems.
- Select one cell so the scope is not accidentally a selection.
- Open Print Preview (Ctrl+P) and step through every page.
- Confirm the page count in the preview matches what you expect.
- Check that title rows repeat and that page numbers show "Page X of Y".
- Confirm hidden sheets are really hidden and that no sheet is accidentally grouped.
- Confirm the paper size is the one the reader will print on.
Page Break Preview from the earlier chapter is the fastest way to find a stray column pushing content onto an extra page.
What the PDF does not keep
A PDF is a fixed picture of the printed output, with some extras. Know what carries over:
- Formulas and values. The PDF contains the displayed text only. Formulas are not included, and the reader cannot recalculate anything.
- Hyperlinks. Cell hyperlinks stay clickable in a PDF made with Excel's own writer. They are lost with the Microsoft Print to PDF printer.
- Comments and notes. They appear only if the Sheet tab of Page Setup tells Excel to print them, either at the end of the sheet or as displayed on the sheet.
- Cell errors. They print as shown unless you set "Cell errors as" to blank,
--, or#N/Ain Page Setup. - Hidden rows and columns. They stay hidden and take no space in the output.
- Charts and shapes. They export as vector graphics when possible, so they stay sharp when zoomed.
Text exported by Excel's writer is real, searchable text with embedded fonts, not an image. If a font cannot be embedded, the viewer may substitute another, which can change line breaks slightly.
Exporting with VBA
Manual export is fine for one-off reports. When you export the same report every week, a macro is faster and removes the scope mistakes described above. The ExportAsFixedFormat method exists on Workbook, Worksheet, and Range objects, which map to the three scopes.
The following macro exports the active sheet. It respects the print area and page setup already defined, and it does not open the file afterward.
Sub ExportSheetToPdf()
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\Report.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End SubKey arguments:
TypeisxlTypePDFfor PDF (the other value isxlTypeXPS).Filenameis the full path. If the file already exists, Excel overwrites it without asking.QualityisxlQualityStandardorxlQualityMinimum, matching "Optimize for".IgnorePrintAreasset toFalsekeeps the print area in force.OpenAfterPublishset toTrueopens the PDF in the default viewer.FromandTolimit the page range.
ThisWorkbook.Path is empty for a workbook that has never been saved, so the macro would write to \Report.pdf at the drive root and probably fail. Save the workbook first.
Changing the scope only means changing the object:
ThisWorkbook.ExportAsFixedFormatexports every visible sheet.Selection.ExportAsFixedFormatexports the current selection.Worksheets("Summary").ExportAsFixedFormatexports a named sheet without activating it.
The next macro applies the page setup from the earlier chapters first, so the output no longer depends on how the sheet was left.
Sub SetupReportPage()
With ActiveSheet.PageSetup
.PrintArea = "$A$1:$H$60"
.Orientation = xlLandscape
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = False
.PrintTitleRows = "$1:$1"
.CenterFooter = "Page &P of &N"
End With
End SubSetting .Zoom = False is required. Without it, Excel ignores FitToPagesWide and FitToPagesTall and uses the percentage zoom instead.
You can run SetupReportPage and then ExportSheetToPdf from a third macro. Reading page setup through VBA can be slow, because Excel asks the printer driver for each property. If a macro that sets many properties runs slowly, set Application.PrintCommunication = False before the With block and True afterward. This sends the changes to the printer in one batch.
Footer codes
The footer in the macro uses codes that Excel replaces at print time. They work in custom headers and footers typed into the dialog as well.
&F File name
&A Sheet name
&D Current date
&P Page number
&N Total number of pages
Page &P of &NCommon errors when exporting
| Symptom | Likely cause | Fix |
|---|---|---|
| PDF contains only a few cells | A range was selected when you exported | Click one cell, then export again |
| PDF has extra blank pages | Formatting or stray values beyond the print area, or Ignore print areas is on | Set a print area, clear the extra cells, turn off Ignore print areas |
| A sheet is missing | The sheet is hidden, or scope was Active sheet(s) | Unhide it, or choose Entire workbook |
| Columns are cut off across pages | Scaling is 100% and the sheet is wider than the page | Use Fit to 1 page wide |
| Page numbers read "Page 1 of 1" on every sheet | Each sheet is numbered on its own when sheets are exported separately | Export as one workbook, or accept per-sheet numbering |
| Macro error "Document not saved" | The target path is invalid or the file is open in a viewer | Close the old PDF and check the path |
| Links do not work | The file was made with the Print to PDF printer | Use Export or Save As |
The last point on the file lock is worth remembering. Some PDF viewers lock the file while it is open. A macro that overwrites Report.pdf then fails with a run-time error. Close the viewer, or add a timestamp to the file name.
Sub ExportWithTimestamp()
Dim target As String
target = ThisWorkbook.Path & "\Report_" & Format(Now, "yyyymmdd_hhnn") & ".pdf"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=target
End SubExercise
You select cells B2:D10 on the Summary sheet, open File > Export, and publish with the default options. The PDF holds only those nine cells. Why, and what two ways can you use to get the whole sheet?
Show answer
Excel defaults the Publish what option to Selection when a multi-cell range is selected, so only that range is exported. Either click a single cell and export again, or open Options and choose Active sheet(s) before publishing. In VBA, call ActiveSheet.ExportAsFixedFormat instead of Selection.ExportAsFixedFormat.
Exercise
A macro sets FitToPagesWide = 1 and FitToPagesTall = False, but the exported PDF still spills across several pages horizontally. What property is probably missing, and where does it go?
Show answer
Zoom = False. It must be set to False inside the same With ActiveSheet.PageSetup block. Without it, Excel uses the percentage zoom and ignores the fit-to-pages values.
Exercise
You need a workbook of six sheets exported as one PDF, but the Raw Data and Calc sheets must be left out. Describe how to do this without deleting them, and name the VBA call that exports the result.
Show answer
Hide the Raw Data and Calc sheets, then choose Entire workbook in the export options. Excel skips hidden sheets. In VBA, call ThisWorkbook.ExportAsFixedFormat with Type:=xlTypePDF and a Filename. Unhide the sheets afterward if you need them visible.