Sub topic 12
Automating Page Setup and PDF Export with VBA
This chapter assumes you can set a print area, orientation, scaling, print titles, and footers from the ribbon, and that you have exported a sheet to PDF by hand. It also assumes you can open the Visual Basic Editor (Alt+F11) and insert a module. Here you will turn those manual steps into two short macros.
Why automate page setup
Every setting you used in earlier chapters lives in one object, PageSetup. When you set up the same layout for many sheets or run a monthly report, repeating the clicks wastes time and invites mistakes. A macro applies identical settings every time.
The PageSetup object belongs to a worksheet. Each property matches a ribbon option you already know.
| Ribbon setting | PageSetup property |
|---|---|
| Print Area | `.PrintArea` |
| Orientation | `.Orientation` |
| Fit to pages wide and tall | `.Zoom`, `.FitToPagesWide`, `.FitToPagesTall` |
| Print Titles, rows to repeat | `.PrintTitleRows` |
| Footer text | `.CenterFooter` |
A macro that sets up the page
This macro configures 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 SubThree details matter here.
.Zoom = Falsemust come before the fit settings. While.Zoomholds a number, Excel uses that percentage and ignores.FitToPagesWideand.FitToPagesTall..FitToPagesTall = Falsemeans "as many pages as needed". Setting it to a number forces the content onto that many pages, which can shrink the text.&Pand&Nare header and footer codes.&Pis the page number and&Nis the total page count. Other codes include&Ffor the file name,&Afor the sheet name, and&Dfor the date. You can combine them with plain text, as inPage &P of &N.
A macro that exports to PDF
Once the page setup is in place, you can export the sheet.
Sub ExportSheetToPdf()
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=ThisWorkbook.Path & "\Report.pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End SubIgnorePrintAreas:=False tells Excel to respect the print area you defined. If you set it to True, Excel exports the whole used range instead. Quality:=xlQualityStandard suits files you will email or print. Use xlQualityMinimum for smaller files that are only read on screen. ThisWorkbook.Path is the folder that holds the workbook, so the PDF lands next to it.
Running both together
A third macro can call the other two so one click does the whole job.
Sub BuildReportPdf()
SetupReportPage
ExportSheetToPdf
End SubAssign it to a button or run it from the Macros dialog (Alt+F8). Because the macros act on ActiveSheet, select the right sheet first. To target a specific sheet, replace ActiveSheet with Worksheets("Sales").
Common errors
- Error 1004 when setting PageSetup. Excel reads printer information to build page settings. It can fail if no printer is installed, or if the default printer is offline or a network printer that is not reachable. Install a local printer driver, such as the Microsoft Print to PDF printer, or switch the default printer.
- The PDF has the wrong number of pages. Check that
.Zoom = Falseruns before the fit settings, and thatIgnorePrintAreasisFalse. - The file is not saved where you expect.
ThisWorkbook.Pathis empty for a workbook that has never been saved. Save it first. - Backslash in the path. The path separator in the examples is for Windows. On Mac, use a forward slash and expect extra file permission prompts.
Exercise
Exercise
You run SetupReportPage, but the sheet still prints at 100% across three pages wide. The macro has .FitToPagesWide = 1 and .FitToPagesTall = False, but the line .Zoom = False was deleted. Why does the sheet ignore the fit settings, and what fixes it?
Show answer
While .Zoom holds a percentage, Excel scales by that percentage and ignores .FitToPagesWide and .FitToPagesTall. Restoring .Zoom = False switches Excel to the fit-to-pages mode, so the sheet is scaled to one page wide.
Exercise
Change ExportSheetToPdf so it exports the worksheet named "Summary" and saves the file as Summary.pdf in the workbook's folder, whatever sheet is active.
Show answer
Replace ActiveSheet with Worksheets("Summary") and change the file name: Worksheets("Summary").ExportAsFixedFormat Type:=xlTypePDF, Filename:=ThisWorkbook.Path & "\Summary.pdf". The other arguments can stay the same.