VBA macros · Printing and PDF

VBA macro to export a range as PDF in Excel

Save the selected range (an invoice, a summary block, a chart area) as a PDF with a date in the file name, then open it.

Windows + Mac

Often you do not want the whole sheet as a PDF, only a block of it: the invoice area, the summary table, the chart and its notes. Setting a print area, exporting and resetting the print area again is fiddly. This macro exports exactly the selected range to a PDF named after the sheet plus the date and time, saved next to the workbook, and opens it so you can check it.

VBA
Option Explicit

Sub ExportRangeAsPdf()
    Dim rng As Range
    Dim wb As Workbook
    Dim fileName As String

    If TypeName(Selection) <> "Range" Then
        MsgBox "Select a range first.", vbExclamation
        Exit Sub
    End If
    Set rng = Selection
    Set wb = rng.Worksheet.Parent
    If Len(wb.Path) = 0 Then
        MsgBox "Save the workbook first; the PDF goes into its folder.", vbExclamation
        Exit Sub
    End If

    fileName = wb.Path & Application.PathSeparator & CleanName(rng.Worksheet.Name) & _
               " " & Format(Now, "yyyy-mm-dd hh-nn") & ".pdf"

    On Error GoTo Fail
    rng.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fileName, _
        Quality:=xlQualityStandard, IncludeDocProperties:=False, _
        IgnorePrintAreas:=True, OpenAfterPublish:=True
    Exit Sub

Fail:
    MsgBox "Could not create the PDF: " & 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 Function
Export the selected range to a dated PDF

How to use it

  1. Open the workbook and press Alt+F11 (Mac: Opt+F11 or Fn+Opt+F11) to open the VBA editor. See The Developer tab and the VBA editor if you have never used it.
  2. Choose Insert › Module. An empty code window opens on the right.
  3. Paste the whole code into that window. If the module already starts with Option Explicit, do not paste that line twice.
  4. Go back to Excel, press Alt+F8 (Mac: Opt+F8, or Tools › Macro › Macros), pick ExportRangeAsPdf and click Run.
  5. Select the range you want in the PDF, then run the macro.
  6. 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

The selection is checked with TypeName(Selection): if a chart or shape is selected, Selection is not a range and the export would fail. The workbook must have been saved because the PDF goes into the same folder.

The file name combines the sheet name, cleaned of characters that file names may not contain, with Format(Now, "yyyy-mm-dd hh-nn"), so exporting twice in a day gives two files instead of overwriting the first. nn stands for minutes; mm would be the month.

Range.ExportAsFixedFormat works like the worksheet version but prints only the given cells. IgnorePrintAreas:=True makes sure a print area set on the sheet does not interfere, and OpenAfterPublish:=True opens the PDF in your default viewer. Page settings such as orientation, margins, headers and footers still come from the sheet's Page Layout settings.

Change it

To always export the same block without selecting it, give the block a name (select it, type InvoiceArea in the Name Box, press Enter) and replace Set rng = Selection with Set rng = ActiveSheet.Range("InvoiceArea"). That is a good fit for templates such as the one in Final project: build a PDF invoice generator in VBA.

To fit the range on one page, set the page setup before exporting. Page setup calls are slow, so only change what you need:

VBA
    With rng.Worksheet.PageSetup
        .Orientation = xlLandscape
        .Zoom = False
        .FitToPagesWide = 1
        .FitToPagesTall = 1
    End With
Fit the exported range on one landscape page

To let the user pick the file name on Windows, use Application.GetSaveAsFilename(fileName, "PDF files (*.pdf), *.pdf"), which returns False on Cancel. To export every sheet instead, see VBA macro to save each sheet as a separate PDF in Excel. To email the PDF from Outlook, attach fileName with the code in VBA macro to send the active workbook by Outlook email.

What can go wrong

A selection made of several separate blocks (Ctrl+click) is exported with each block on its own page. Hidden rows and columns inside the range are not printed, which is usually what you want.

Watch out. If a PDF with the same name is open in a viewer, the export fails with Document not saved. Close the PDF and run the macro again. A printer driver must be installed for Excel to lay out pages; Microsoft Print to PDF is enough.
Tip. Works on Windows (Excel 2010 and later) and Mac (Excel 2016 and later). On a Mac, OpenAfterPublish may be ignored and you may be asked to grant access to the folder the first time.

Related: VBA macro to save each sheet as a separate PDF in Excel, VBA macro to send a range in the body of an Outlook email.

More vba macros