Sub topic 12
Automating Page Setup and PDF Export with VBA
What this chapter assumes
You have used the Page Layout tab, Page Break Preview, and the Export to PDF command in the earlier chapters. You can open the Visual Basic Editor (Alt+F11), insert a module, and run a macro. You do not need to know VBA well. Every procedure below is short and explained line by line.
VBA (Visual Basic for Applications) is the macro language built into Excel. Everything you set in the Page Setup dialog box has a matching VBA property, so a macro can apply the same layout every time.
Why automate page setup
Page setup is stored per worksheet. If you produce a monthly report with a dozen sheets, you repeat the same clicks on each one, and any sheet you miss prints differently. A macro gives you three things:
- The same settings on every sheet, every time.
- A record of the settings in code, which you can review and change in one place.
- A one-click export that writes a PDF with a predictable name and location.
Automation pays off when you repeat a job or when several people must produce identical output. For a one-off sheet, the ribbon is faster.
The PageSetup object
Each worksheet has a PageSetup object. You read and write its properties to change the layout. This macro applies the settings from the earlier chapters to the active sheet:
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 SubThe With block means every line that starts with a dot refers to ActiveSheet.PageSetup. The table links each property to the setting you already know from the ribbon.
| Property | Ribbon equivalent | Typical value |
|---|---|---|
| `PrintArea` | Print Area > Set Print Area | `"$A$1:$H$60"` (a string, absolute references) |
| `Orientation` | Orientation | `xlPortrait` or `xlLandscape` |
| `PaperSize` | Size | `xlPaperA4`, `xlPaperLetter` |
| `LeftMargin`, `RightMargin`, `TopMargin`, `BottomMargin` | Margins | Values in points |
| `Zoom` | Scale to Fit | `False` to use fit-to-pages, or a number from 10 to 400 |
| `FitToPagesWide`, `FitToPagesTall` | Width, Height | A whole number, or `False` for automatic |
| `PrintTitleRows`, `PrintTitleColumns` | Print Titles | `"$1:$1"`, `"$A:$A"` |
| `CenterHorizontally` | Center on page | `True` or `False` |
| `PrintGridlines`, `PrintHeadings` | Sheet Options > Print | `True` or `False` |
| `PrintComments` | Comments and notes | `xlPrintNoComments`, `xlPrintSheetEnd`, `xlPrintInPlace` |
| `PrintErrors` | Cell errors as | `xlPrintErrorsDisplayed`, `xlPrintErrorsBlank` |
Margins are measured in points
Margin properties use points, not inches. One inch is 72 points. Convert with Application.InchesToPoints so the code reads naturally:
Sub SetMargins()
With ActiveSheet.PageSetup
.PaperSize = xlPaperA4
.LeftMargin = Application.InchesToPoints(0.7)
.RightMargin = Application.InchesToPoints(0.7)
.TopMargin = Application.InchesToPoints(0.75)
.BottomMargin = Application.InchesToPoints(0.75)
.HeaderMargin = Application.InchesToPoints(0.3)
.FooterMargin = Application.InchesToPoints(0.3)
.CenterHorizontally = True
End With
End SubThe scaling rule that trips people up
Zoom and the two FitToPages properties are linked. If Zoom holds a number, Excel uses that percentage and ignores FitToPagesWide and FitToPagesTall. To use fit-to-pages, set Zoom = False first. In the macro above, .Zoom = False comes before the FitToPages lines for that reason.
Setting .FitToPagesTall = False means "as many pages tall as needed", the same as leaving the Height box on Automatic.
Header and footer codes
The header and footer properties are LeftHeader, CenterHeader, RightHeader, LeftFooter, CenterFooter, and RightFooter. Each takes a string. Codes that start with & are replaced when Excel prints.
| Code | Prints |
|---|---|
| `&F` | File name |
| `&A` | Sheet name |
| `&D` | Current date |
| `&T` | Current time |
| `&P` | Page number |
| `&N` | Total number of pages |
| `&&` | A literal ampersand |
A footer such as "Page &P of &N" works as shown. Two details matter:
- To print an actual
&in text like "Sales & Marketing", type&&. A single&followed by a letter is read as a code. - Header and footer strings are limited to 255 characters. Long strings fail with a runtime error.
Exporting to PDF
ExportAsFixedFormat writes a PDF without opening a print dialog. It uses the page setup that is already on the sheet, so set up the page first and export second.
Sub ExportSheetToPdf()
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\Report.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub| Argument | Meaning |
|---|---|
| `Type` | `xlTypePDF` for PDF (the other value is `xlTypeXPS`) |
| `Filename` | Full path including the `.pdf` extension. An existing file with the same name is overwritten without a prompt |
| `Quality` | `xlQualityStandard` for print, `xlQualityMinimum` for smaller files |
| `IncludeDocProperties` | Whether author and title properties are written into the PDF |
| `IgnorePrintAreas` | `False` respects the print area. `True` exports the entire used range |
| `From`, `To` | Optional page numbers to export a range of pages |
| `OpenAfterPublish` | Opens the PDF in the default viewer when done |
Choosing what to export
The object you call the method on decides the scope.
| Call it on | Result |
|---|---|
| `ActiveSheet` or a `Worksheet` | That one sheet |
| `Selection` or a `Range` | Only that range. A print area on the sheet does not apply |
| `ThisWorkbook` or `ActiveWorkbook` | All visible sheets, in tab order, in a single PDF |
| `ActiveWindow.SelectedSheets` | Only the sheets currently grouped by selection |
Hidden sheets are skipped in a workbook export. Sheets that have no printable content are also skipped.
The path separator
The first example builds a path with "\", which works on Windows only. Use Application.PathSeparator if the macro may run on a Mac:
Dim pdfPath As String
pdfPath = ThisWorkbook.Path & Application.PathSeparator & "Report.pdf"ThisWorkbook.Path is an empty string when the workbook has never been saved. The result would be a path starting at the drive root, so test for that case before exporting.
Putting it together
The macro below separates the work into two procedures. ApplyReportSetup formats one sheet. ExportReport applies it to every visible worksheet, then writes one PDF with a dated name.
Option Explicit
Sub ApplyReportSetup(ByVal ws As Worksheet)
With ws.PageSetup
.Orientation = xlLandscape
.PaperSize = xlPaperA4
.LeftMargin = Application.InchesToPoints(0.5)
.RightMargin = Application.InchesToPoints(0.5)
.TopMargin = Application.InchesToPoints(0.75)
.BottomMargin = Application.InchesToPoints(0.75)
.CenterHorizontally = True
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = False
.PrintTitleRows = "$1:$1"
.PrintGridlines = False
.PrintErrors = xlPrintErrorsBlank
.LeftFooter = "&F - &A"
.CenterFooter = "Page &P of &N"
.RightFooter = "&D"
End With
End Sub
Sub ExportReport()
Dim ws As Worksheet
Dim pdfPath As String
If ThisWorkbook.Path = "" Then
MsgBox "Save the workbook first so the PDF has a folder.", vbExclamation
Exit Sub
End If
pdfPath = ThisWorkbook.Path & Application.PathSeparator & _
"Report_" & Format(Date, "yyyy-mm-dd") & ".pdf"
On Error GoTo Failed
Application.ScreenUpdating = False
For Each ws In ThisWorkbook.Worksheets
If ws.Visible = xlSheetVisible Then ApplyReportSetup ws
Next ws
ThisWorkbook.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=pdfPath, _
Quality:=xlQualityStandard, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Application.ScreenUpdating = True
MsgBox "Saved " & pdfPath, vbInformation
Exit Sub
Failed:
Application.ScreenUpdating = True
MsgBox "Export failed: " & Err.Description, vbCritical
End SubPoints worth noting:
Option Explicitforces you to declare variables, which catches typos.ByVal ws As Worksheetlets you callApplyReportSetupon any sheet, not only the active one.- The error handler turns
ScreenUpdatingback on. If the macro stopped after turning it off, Excel would look frozen. - The macro does not set
PrintArea. A sheet with no print area prints its used range, which is correct for sheets that grow. Add a print area only for sheets with a fixed layout.
How the pieces fit
Gotchas and common errors
Speed
Each PageSetup assignment can make Excel talk to the printer driver, which is slow. On sheets with many assignments, the macro may take several seconds per sheet. Excel 2010 and later let you pause that communication:
Sub FastSetup()
Application.PrintCommunication = False
With ActiveSheet.PageSetup
.Orientation = xlLandscape
.Zoom = False
.FitToPagesWide = 1
.FitToPagesTall = False
End With
Application.PrintCommunication = True
End SubAlways set it back to True. If an error occurs between the two lines, the setting stays off, so put the reset in your error handler as well.
Errors without a printer
Setting PageSetup properties can raise error 1004 ("Unable to set the Orientation property of the PageSetup class") when no default printer is installed or the printer is offline. The settings depend on the printer driver. Installing any printer, including Microsoft Print to PDF, usually removes the error. Different drivers also report slightly different printable areas, so a layout that fits exactly on one machine can spill by a column on another. Leave a small margin of safety.
Other frequent failures
- Run-time error 1004 on export. The file is open in a PDF viewer, the folder does not exist, or the path contains characters that Windows rejects. Close the file, check the folder, and keep file names free of
\ / : * ? " < > |. - Blank or missing pages. Hidden sheets and sheets with no data are skipped. Cells that contain only formatting can still create empty pages, so check the print area.
- PDF has the wrong scale. The sheet still has a numeric
Zoom. Set it toFalsebefore the fit properties. - Settings seem to vanish.
PageSetupbelongs to each sheet. A new sheet does not inherit settings from another, so your macro must apply them to it. - Title rows missing.
PrintTitleRowsneeds a string like"$1:$1". ARangeobject is not accepted.
Where to keep the macro
Macros require a macro-enabled file. Save the workbook as .xlsm. A macro stored in the workbook only runs when that workbook is open. To make the macro available to every workbook, store it in your Personal Macro Workbook. Another option is to add a button on the sheet and assign the macro to it, which suits colleagues who do not open the code editor.
Exercise
A macro sets .FitToPagesWide = 1 and .FitToPagesTall = False, but the exported PDF still prints at 100% and spills across several pages wide. What is the most likely cause, and what line fixes it?
Show answer
Zoom still holds a number, so Excel ignores the fit-to-pages properties. Add .Zoom = False before the FitToPages lines inside the With ws.PageSetup block.
Exercise
You call ActiveSheet.Range("A1:D20").ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\Temp\Part.pdf" on a sheet that has a print area of $A$1:$H$60. Which cells appear in the PDF, and which call would export the whole print area instead?
Show answer
Only A1:D20 appears, because the scope is set by the object you call the method on. To export the whole print area, call ActiveSheet.ExportAsFixedFormat with IgnorePrintAreas:=False.
Exercise
Modify ExportReport so that the PDF contains only the sheet named "Summary" and is saved as Summary.pdf in the workbook folder.
Show answer
Remove the loop and call ApplyReportSetup ThisWorkbook.Worksheets("Summary"). Then call ThisWorkbook.Worksheets("Summary").ExportAsFixedFormat Type:=xlTypePDF, Filename:=ThisWorkbook.Path & Application.PathSeparator & "Summary.pdf".