Excel VBA to Export Selected Sheets to PDF
Categories:
Exporting Selected Excel Sheets to PDF with VBA

Learn how to use VBA to programmatically select specific worksheets in an Excel workbook and export them as a single PDF file, enhancing automation and reporting.
Microsoft Excel is a powerful tool for data management and analysis. Often, after preparing your data across multiple sheets, you need to share specific views or reports in a universally accessible format like PDF. Manually selecting and exporting sheets can be tedious and error-prone, especially with large workbooks or frequent reporting needs. This article will guide you through creating a VBA macro to automate the process of selecting desired sheets and exporting them into a single PDF document.
Understanding the Core VBA Export Functionality
Excel's VBA object model provides the ExportAsFixedFormat method, which is central to converting worksheets or workbooks to PDF. This method is available on Workbook and Sheets objects. When exporting multiple sheets, it's crucial to select them programmatically before calling the export method. The key is to create an array of sheet names or objects and then use the Sheets(Array(...)) syntax to activate the selection.
Sub ExportSelectedSheetsToPDF()
Dim ws As Worksheet
Dim selectedSheets As Variant
Dim pdfFileName As String
Dim folderPath As String
' Define the sheets you want to export
' You can modify this array to include the names of your desired sheets
selectedSheets = Array("Sheet1", "Report_Summary", "Data_Analysis")
' Define the folder path where the PDF will be saved
' Ensure this folder exists or the macro will error
folderPath = ThisWorkbook.Path & "\PDF_Exports\"
' Create the folder if it doesn't exist
If Dir(folderPath, vbDirectory) = "" Then
MkDir folderPath
End If
' Define the PDF file name
pdfFileName = folderPath & "Selected_Sheets_Report_" & Format(Now, "yyyymmdd_hhmmss") & ".pdf"
On Error GoTo ErrorHandler
' Select the sheets to be exported
' This is the critical step for exporting multiple sheets as one PDF
ThisWorkbook.Sheets(selectedSheets).Select
' Export the selected sheets as a PDF
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=pdfFileName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
MsgBox "Selected sheets exported to PDF successfully!", vbInformation
' Deselect sheets and return to a single active sheet (optional but good practice)
ThisWorkbook.Sheets("Sheet1").Select
Exit Sub
ErrorHandler:
MsgBox "An error occurred: " & Err.Description, vbCritical
' Deselect sheets in case of error too
ThisWorkbook.Sheets("Sheet1").Select
End Sub
VBA macro to export specific sheets to a single PDF file.
Customizing Your Export Macro
The provided VBA code is a solid starting point, but you can customize it further to fit specific needs. Consider how you might dynamically select sheets, handle different output paths, or manage error conditions more robustly. For instance, you might want to prompt the user for the sheets to export or the save location, or even loop through a list of sheets defined in a separate configuration sheet.
MkDir command to create the folder if it's missing, which is a good practice to prevent runtime errors.
Workflow for exporting selected Excel sheets to PDF using VBA.
Advanced Considerations and Best Practices
When working with VBA for PDF exports, there are several advanced considerations. You might want to include error handling to gracefully manage situations where a specified sheet doesn't exist or the save path is invalid. Additionally, controlling print settings (like page orientation, margins, and scaling) before export can significantly impact the PDF's appearance. The ExportAsFixedFormat method offers parameters like Quality and IncludeDocProperties that can be fine-tuned.
Sub ExportSelectedSheetsWithPrintSettings()
Dim ws As Worksheet
Dim selectedSheets As Variant
Dim pdfFileName As String
Dim folderPath As String
selectedSheets = Array("Sheet1", "Report_Summary")
folderPath = ThisWorkbook.Path & "\PDF_Exports\"
If Dir(folderPath, vbDirectory) = "" Then MkDir folderPath
pdfFileName = folderPath & "Custom_Report_" & Format(Now, "yyyymmdd_hhmmss") & ".pdf"
On Error GoTo ErrorHandler
' Temporarily select sheets to apply print settings
ThisWorkbook.Sheets(selectedSheets).Select
' Apply custom print settings to the selected sheets
With ActiveSheet.PageSetup
.Orientation = xlLandscape ' Set to landscape
.Zoom = False ' Disable automatic scaling
.FitToPagesWide = 1 ' Fit to 1 page wide
.FitToPagesTall = False ' Allow multiple pages tall
.LeftMargin = Application.InchesToPoints(0.5)
.RightMargin = Application.InchesToPoints(0.5)
.TopMargin = Application.InchesToPoints(0.75)
.BottomMargin = Application.InchesToPoints(0.75)
.CenterHorizontally = True
.PrintTitleRows = "$1:$1" ' Example: Repeat row 1 on every page
End With
' Export the selected sheets as a PDF
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=pdfFileName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=True
MsgBox "Selected sheets exported to PDF with custom settings!", vbInformation
' Deselect sheets and return to a single active sheet
ThisWorkbook.Sheets("Sheet1").Select
Exit Sub
ErrorHandler:
MsgBox "An error occurred: " & Err.Description, vbCritical
ThisWorkbook.Sheets("Sheet1").Select
End Sub
VBA macro with custom print settings applied before PDF export.
PageSetup properties on ActiveSheet will apply those settings to all currently selected sheets. If you need different print settings for different sheets within the same PDF export, you would need to export them individually and then merge the PDFs using external tools or more advanced VBA techniques.1. Open your Excel workbook
Ensure the workbook containing the sheets you wish to export is open.
2. Access the VBA editor
Press Alt + F11 to open the Visual Basic for Applications editor.
3. Insert a new module
In the VBA editor, right-click on your workbook name in the Project Explorer, then select Insert > Module.
4. Paste the VBA code
Copy the provided VBA code (e.g., ExportSelectedSheetsToPDF) and paste it into the new module window.
5. Customize sheet names and path
Modify the selectedSheets array to include the exact names of the sheets you want to export. Adjust folderPath if you want to save the PDF in a different location.
6. Run the macro
Place your cursor anywhere inside the Sub routine and press F5, or go to Developer > Macros, select ExportSelectedSheetsToPDF, and click Run.