How to save specific multiple worksheets to a pdf file programmatically
This article demonstrates macros that save worksheets to a single pdf file.
What's on this webpage
1. Export all worksheets in workbook to PDF programmatically
Exporting all worksheets in a workbook to PDF programmatically can be useful for several reasons:
- Batch processing: Automating the export process saves time and effort, especially when dealing with large workbooks or multiple workbooks.
- Consistency: Ensures that all worksheets are exported in a consistent format. PDF readers can be geted for free, everyone can open and access the files.
- Sharing and collaboration: PDFs are widely supported and can be easily shared with others, making it a convenient format for collaboration and review.
- Archiving: Exporting worksheets to PDF creates a snapshot of the data at a particular point in time, making it useful for archiving and auditing purposes.
- Reporting: PDFs can be used to generate reports that can be easily distributed to stakeholders, such as management, customers, or regulatory bodies.
- Easy integration: PDFs can be easily integrated into other systems, such as document management systems, or used as input for other processes, such as data analysis or machine learning.
- Security: PDFs show only the selected worksheets, not the formulas and data behind the formulas.
By exporting all worksheets in a workbook to PDF programmatically, you can automate this process and take advantage of these benefits.
The following macro saves all worksheets in the active workbook to a single pdf file.
'Name macro Sub ExportWbtoPdf() 'Select all worksheets in active workbook For Each WS In ActiveWorkbook.Worksheets Worksheets(WS.Name).Select False Next WS 'Ask for a directory to save the pdf file in With Application.FileDialog(msoFileDialogFolderPicker) .Show myfolder = .SelectedItems(1) & "\" End With 'Ask for a save file name for the pdf file myfile = InputBox("Enter file name", "Save as..") 'Save all worksheets in workbook to pdf file ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ myfolder & myfile _ , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _ :=False, OpenAfterPublish:=True End Sub
1.1 How to start the macro?
After you have saved the above code to a code module you can start the macro by:
- Go to the "Developer" tab on the ribbon.
- Press with left mouse button on the "Macros" button, a dialog box appears.
- Select macro name "ExportWbtoPdf()"
- Press with left mouse button on the "Run" button.
1.2 How to use the macro?
- The macro shows a input box or a dialog box after starting the macro.
- Type the file name in the input box.
- Press with left mouse button on the "OK" button.
The macro now saves each worksheet in the workbook to the pdf file name you specified.
2. How to save specific multiple worksheets to a pdf file programmatically
'Name macro Sub SaveSelectedSheetsToPDF() 'Dimension variables and declare data types Dim str As String, myfolder As String, myfile As String 'Get names from worksheets str = "Do you want to save these sheets to a single pdf file?" & Chr(10) For Each sht In ActiveWindow.SelectedSheets str = str & sht.Name & Chr(10) Next sht 'Display Message box answer = MsgBox(str, vbYesNo, "Continue with save?") If answer = vbNo Then Exit Sub 'Pick a directory With Application.FileDialog(msoFileDialogFolderPicker) .Show myfolder = .SelectedItems(1) & "\" End With 'Ask for folder myfile = InputBox("Enter filename", "Save as..") 'Save pdf file ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ myfolder & myfile _ , Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _ :=False, OpenAfterPublish:=True 'Quit macro End Sub
2.1 How to use the macro?
Make sure you select the worksheets you want to save as a single pdf file before you run the macro. To select multiple worksheets press and hold CTRL and then press with left mouse button on with the mouse on the worksheet tabs located at the bottom of your Excel screen.
This happens when you start the macro
- Confirm selected sheets by press with left mouse button oning "Yes".
- A dialog box appears, choose a save folder. Press with left mouse button on OK.
- A new dialog box appears. Enter a file name.
- Press with left mouse button on OK button.
- A pdf file is created and opens automatically.
3. Where do I put the code in my workbook?
- Start the Visual Basic Editor (Alt+F11).
- Press with left mouse button on "Insert" on the top menu, see image above.
- Press with left mouse button on "Module".
- Paste code to window.
- Return to Excel.
4. Assign macro to a button for quick access
- Go to tab "Developer" on the ribbon
- Press with left mouse button on "Insert" button
- Press with left mouse button on "Button (Form Control)
- Press with left mouse button on and drag on sheet to build a button
- Assign macro SaveSelectedSheetsToPDF
- Press with left mouse button on OK
5. Save the macro in your personal macro workbook
If you save the macro in a personal macro workbook, you can access that macro no matter what workbook you have open.
Read this: Copy your macros to a Personal Macro Workbook
Macro category
Table of Contents How to create an interactive Excel chart How to filter chart data How to build an interactive […]
Table of Contents Excel monthly calendar - VBA Calendar Drop down lists Headers Calculating dates (formula) Conditional formatting Today Dates […]
Table of Contents Split data across multiple sheets - VBA Add values to worksheets based on a condition - VBA […]
Excel categories
13 Responses to “How to save specific multiple worksheets to a pdf file programmatically”
Leave a Reply
How to comment
How to add a formula to your comment
<code>Insert your formula here.</code>
Convert less than and larger than signs
Use html character entities instead of less than and larger than signs.
< becomes < and > becomes >
How to add VBA code to your comment
[vb 1="vbnet" language=","]
Put your VBA code here.
[/vb]
How to add a picture to your comment:
Upload picture to postimage.org or imgur
Paste image link to your comment.
Contact Oscar
You can contact me through this contact form
Hi Oscar
First of all thanks for your beautiful macro to copy an Excel file to PDF. If you want to copy a wide horizontal field to PDF, it can cause a split in the PDF: you get divided the text, graphics and / or object on two pages). That's not what you want!
To make a perfect horizontal layout, I recommend to define first in the worksheet: Print Range, Page Layout (on ribbon). Create with File / Print Options other necessary instructions, for example, choose settings like "print to fit", borders etc.etc. The actual print layout is displayed on the right side.
Instead of a normal print, you can now activate the Macro. These simple adjustments don't give a distribution on two pages, but an appropriate horizontal PDF format. So, it's a contribution to your readers.
Best regards,
Bert van Zandbergen
Bert van Zandbergen,
thank you for commenting.
Hi, Oscar
your code works great but it only prints excel sheets that have been individually selected before running the macro. is there a way to get the code to automatically select all unhidden sheets in excel and then print to pdf.
The reason why i say unhidden sheets is, because i have a large userform that based on user selections hides unneeded excel sheets. so i would only need to print the relevant sheets, which would be the unhidden sheets.
thanks for your time,
Tyler Estrada
Hi Oscar
thanks for the great effort
one question
if I want to export each sheet as a separate pdf file, what should be changed in the code?
Thanks
Mohamed
Hi,
I just found the error: I also opened the xlsm file, had a look at the code there, and found that it differs from the code at the top of this article (I copied the code from there first).
The difference was in the "amp;amp;amp;amp" portion.
After removing these, the macro is running smooth now.
Cheers
Luc
Oscar - Many, many thks for this, it was an excellent post, and a great solution for what I was looking for. One question, I was wondering how to do this based on a validation list. For example, lets say I have 10 sheets. I have a drop down list say in A1 of Sheet1, which the workbook menu. The drop down list contains - say two reports - Short Report and Long Report.
If I press with left mouse button on Short Report, it will print pages - 2,3, and 5. If I select Long Report, it will print pages 2, 6,7,8,9, and 10.
I would like to have the same option for a single PDF file. Thus, if I select Short Report, pages 2, 3 and 5 will be saved in a single PDF file. Any assistance on this would be greatly appreciated. cheers
Joe
Dear Sir,
when i run the macro its showing "run time error 5".invalid procedure or call argument.
please help us to solved the issues.
Thanks
Manoj
MANOJ,
WordPress has added characters that shouldn't be in the code, I have tried to remove them. I recommend you try out the attached file.
Dear Sir,
You have recommended to get the attached file but that is not reflecting,is it possible send me through mail([email protected])
Regards
Manoj
Dear Sir,
Please go through the below code and help me to solve the issues that when i run the macro its showing run time error 5".invalid procedure or call argument.
Sub saveinvoice()
Sheet2.Range("a1:l57").ExportAsFixedFormat xlTypePDF, Filename:=" C:\Users\USER\Desktop\inventory\" & Sheet2.Range("j11").Value, openafterpublish:=True
Thanks
Manoj
End Sub
How can you choose which sheet is printed first and which one is printed next?
hussain assani,
You need to rearrange the worksheet tabs to be able to print them in a given order.
To sort the worksheets in a given order you can press with the left mouse button and hold on a worksheet tab and drag to the position you want, see this guide:
https://www.extendoffice.com/documents/excel/3410-excel-change-orders-of-tabs.html#a1
Hi Oscar,
Thanks for your excellent work. The save selected sheets macro is precisely what I needed. However it runs just fine in O365 for Windows but gives me an error on O365 for Mac. Getting a 'Run-time error 91' 'Object variable or With block variable not set'. Tried a few things with the .Show and myfolder variable in the With block but no luck.
Any clues on what might be the problem?
Thanks in advance