Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA to Export Selected Sheets to PDF

Tags:

I'm using the following code to export selected sheets from Excel 2010 to a single pdf file...

ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select

ActiveSheet.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:="C:\temp.pdf", _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=True

My problem is that it only exports the first sheet. Any ideas?

like image 564
thistledownjohn Avatar asked Dec 23 '13 20:12

thistledownjohn


People also ask

How do I Export a selection from Excel to PDF?

Step 1: Select the ranges that you will save as PDF file. If you want to save the entire workbook as one PDF file, just skip this step. Step 2: Click the File > Save as. Step 3: In the Save As dialog box, select the PDF item from the Save as type: drop down list.

How do I save multiple worksheets as one PDF?

If you have multiple worksheets and want to save all of them in the same PDF file, click Options in the Save As dialog box. The Options dialog box will appear. Select Entire workbook, then click OK.


1 Answers

Once you have Selected a group of sheets, you can use Selection

Consider:

Sub luxation()
    ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
    Selection.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:="C:\TestFolder\temp.pdf", _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub

EDIT#1:

Further testing has reveled that this technique depends on the group of cells selected on each worksheet. To get a comprehensive output, use something like:

Sub Macro1()

   Sheets("Sheet1").Activate
   ActiveSheet.UsedRange.Select
   Sheets("Sheet2").Activate
   ActiveSheet.UsedRange.Select
   Sheets("Sheet3").Activate
   ActiveSheet.UsedRange.Select

   ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
   Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
      "C:\Users\James\Desktop\pdfmaker.pdf", Quality:=xlQualityStandard, _
      IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
      True
End Sub
like image 73
Gary's Student Avatar answered Sep 22 '22 04:09

Gary's Student