Note: The other languages of the website are Google-translated. Back to English

How to use Command Button to save active worksheet as PDF file in Excel?

While working in Microsoft Excel, you may face the problem of saving active worksheet as PDF file. In this article, you can learn how to save active worksheet as PDF file with VBA code through a Command Button. And if you also want to save a range or each worksheet in active workbook as individual PDF file, this article can also help you.

Use Command Button to save active worksheet as PDF file with VBA code
Easily save active or each worksheet as individual PDF file with Kutools for Excel


Use Command Button to save active worksheet as PDF file with VBA code

You can run the following VBA code to save an active worksheet as PDF file by clicking on a Command Button. Please do as follows.

1. Firstly, you need to create a folder named PDF for saving your new converted PDF file. Here I create this folder in my local disc (C:).

2. Please insert a Command Button by clicking Developer > Insert > Command Button (ActiveX Control). See screenshot:

2. Then draw a Command Button in to the worksheet you need to add new rows, right click the Command Button and click Properties from the right-clicking menu.

3. In the Properties dialog box, enter the displayed text of the Command Button into the Caption box under the Categorized tab, and then close the dialog box.

You can see the displayed text of the Command Button is changed as below screenshot shown.

4. Right click the Command Button again, and then click View Code from the right-clicking menu.

5. In the opening Microsoft Visual Basic for Applications window, please replace the original code in the Code window with the following VBA code.

VBA code: Command Button to save active worksheet as PDF

Private Sub CommandButton1_Click()
    Application.ScreenUpdating = False
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
            Filename:="C:\PDF\Export.pdf", _
            OpenAfterPublish:=False
    Application.ScreenUpdating = True
End Sub

Note: In the code, CommandButton1 is the Command Button name you will use to save active sheet as PDF file. "C:\PDF\Export.pdf" is the path and name of your saving PDF file.

6. Press the Alt + Q keys simultaneously to close the Microsoft Visual Basic for Applications window. Then turn off the Design Mode under the Developer tab.

Now, click on the Command Button, the active worksheet will be saved as a PDF file named Export and located in the specified location.


Save each worksheet as individual PDF file of active workbook with Kutools for Excel

Here recommend the Split Workbook utility of Kutools for Excel to easily save active worksheet as a PDF file. Besides, you can also save each worksheet in current workbook as individual PDF file with this utility.

Before applying Kutools for Excel, please download and install it firstly.

1. In the workbook you need to save each worksheet as individual PDF file, then click Kutools Plus > Workbook > Split Workbook. See screenshot:

2. In the Split Workbook dialog box, please configure as follows:

2.1) Only check the active sheet name in the Worksheet name box;
2.2) Select PDF (*.pdf) option from the Save as type drop-down list;
2.3) Click the Split button, then a Select Folder dialog pops up, specify a folder to save the PDF file;

Then the selected worksheet is saved as PDF file immediately.

Notes:

1. You can check multiple worksheet names in the Worksheet name box to save them as individual pdf file at once;
2. Except for saving worksheet as pdf files, you can save worksheets as txt. or csv. file as you need.

  If you want to have a free trial (30-day) of this utility, please click to download it, and then go to apply the operation according above steps.


Demo: Save selection or each worksheet as PDF with Kutools for Excel


Related articles:


The Best Office Productivity Tools

Kutools for Excel Solves Most of Your Problems, and Increases Your Productivity by 80%

  • Reuse: Quickly insert complex formulas, charts and anything that you have used before; Encrypt Cells with password; Create Mailing List and send emails...
  • Super Formula Bar (easily edit multiple lines of text and formula); Reading Layout (easily read and edit large numbers of cells); Paste to Filtered Range...
  • Merge Cells/Rows/Columns without losing Data; Split Cells Content; Combine Duplicate Rows/Columns... Prevent Duplicate Cells; Compare Ranges...
  • Select Duplicate or Unique Rows; Select Blank Rows (all cells are empty); Super Find and Fuzzy Find in Many Workbooks; Random Select...
  • Exact Copy Multiple Cells without changing formula reference; Auto Create References to Multiple Sheets; Insert Bullets, Check Boxes and more...
  • Extract Text, Add Text, Remove by Position, Remove Space; Create and Print Paging Subtotals; Convert Between Cells Content and Comments...
  • Super Filter (save and apply filter schemes to other sheets); Advanced Sort by month/week/day, frequency and more; Special Filter by bold, italic...
  • Combine Workbooks and WorkSheets; Merge Tables based on key columns; Split Data into Multiple Sheets; Batch Convert xls, xlsx and PDF...
  • More than 300 powerful features. Supports Office / Excel 2007-2021 and 365. Supports all languages. Easy deploying in your enterprise or organization. Full features 30-day free trial. 60-day money back guarantee.
kte tab 201905

Office Tab Brings Tabbed interface to Office, and Make Your Work Much Easier

  • Enable tabbed editing and reading in Word, Excel, PowerPoint, Publisher, Access, Visio and Project.
  • Open and create multiple documents in new tabs of the same window, rather than in new windows.
  • Increases your productivity by 50%, and reduces hundreds of mouse clicks for you every day!
officetab bottom
Comments (33)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Hi, How would one allow the user to enter the file name as opposed to "Export.pdf"? Thanks, Ian
This comment was minimized by the moderator on the site
Sub SaveAsPDF()
Application.Screen Updating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=Application.InputBox("Enter File Name")

strExcelPath = "H:\My Documents"

Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
I have a similar request I want the file to be named the same as a particular cell in the tab , IE: G19 ( This is the invoice number and I want the file to save as PDF with that name) ? . I have managed to get the export.pdf working but this isn't going to work on multiple saves.Any thoughts thanks
This comment was minimized by the moderator on the site
Good Day,
The following VBA code can help you solve the problem. Please select cell G19 in the popping up Kutoos for Excel dialog box after running the code. Thank you for your comment.

Private Sub CommandButton1_Click()
Dim xRg As Range
Dim xName As String
On Error Resume Next
Application.ScreenUpdating = False
Set xRg = Application.InputBox("Select the cell you will name the PDF with the cell value:", "Kutools for Excel", Selection.Address, , , , , 8)
If xRg Is Nothing Then Exit Sub
xName = xRg(1).Value
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\PDF\" & xName & ".pdf", _
OpenAfterPublish:=False
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
I changed the path to D drive, but it is not saving in the D drive. What to do?
This comment was minimized by the moderator on the site
Hi Akshay M N,
If you have modified the above path to D drive, make sure there is a folder named PDF in your D drive.
If you only want to save the file in the D drive without creating a subfolder, please use this folder path: "C:\" & xName & ".pdf"
This comment was minimized by the moderator on the site
I can convert my files to PDF now with a command button, but can I also get that same function to allow a different name to each file; based on an existed number structure?
This comment was minimized by the moderator on the site
Hi Randy,
Sorry I can’t help with this, welcome to post any question in our forum: https://www.extendoffice.com/forum.html to get more Excel supports from our professional.
This comment was minimized by the moderator on the site
IT SHOWS Run-Time error '1004'
This comment was minimized by the moderator on the site
Hi Nzee,
I need to know your Excel version. Thank you for your comment.
This comment was minimized by the moderator on the site
plz paste coding for save as pdf button in microsoft excel
This comment was minimized by the moderator on the site
How do I do this for MS Word? I have a bunch of questions with radio button options as answers. So I want to create a command button to output the questions with the selected answers only on another word document. How do I do this? A code would really help! I'll email you the document if you need it. Thanks!
This comment was minimized by the moderator on the site
Good day,
Sorry can't help you with that yet.
This comment was minimized by the moderator on the site
Sub ZapiszPDF()
Dim sNazwaPliku As String

sNazwaPliku = ActiveSheet.Name

Application.Dialogs(xlDialogSaveAs).Show sNazwaPliku, 57

End Sub
This comment was minimized by the moderator on the site
ive followed the code, this is what i have:

Private Sub CommandButton2_Click()
Application.ScreenUpdating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=Range("P2"), _
OpenAfterPublish:=True
Application.ScreenUpdating = True
End Sub

i need the file to save to the location that the orignal file is located. also need a copy of the excel file to save aswell with the same name.
This comment was minimized by the moderator on the site
Hi Matt Bentley,
The code works perfectly. Thank you for sharing.
This comment was minimized by the moderator on the site
Hallo,

kann jemand mir helfen?

Ich nutze diese Zeilen und möchte jedoch, das aus dem Blatt ein Zellenwert als Dateiname gespeichert wird:

Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\PDF\Export.pdf", _
OpenAfterPublish:=False
Application.ScreenUpdating = True
End Sub

Danke
This comment was minimized by the moderator on the site
Hallo,

ich nutze diese Zeilen und möchte das eine Zelle als Dateiname verwenden wird!
Kann mir jemand ein Tipp geben?


Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="c:/" & G3 & ".pdf", _
OpenAfterPublish:=False
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Hi Sascha,
The following code can help. Before applying the code, please change 'C:\Users\Win10x64Test\Documents\PDF' in the fourth line to you own destination folder path.
Private Sub CommandButton1_Click()
'Updated by Extendoffice 20220929
    Application.ScreenUpdating = False
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
            Filename:="C:\Users\Win10x64Test\Documents\PDF\" & Range("G3").Value, _
            OpenAfterPublish:=False
    Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Что это за кнопка - "другой" + Q клавиши одновременно" ? Не поняла что нажимать, подскажите, пожалуйста
This comment was minimized by the moderator on the site
Hi Диана,
It is the "Alt" key on your keyboard. Microsoft Excel allows users to press the "Alt" + "Q" keys to close the Microsoft Visual Basic for Applications window and return to the worksheet.
This comment was minimized by the moderator on the site
Goededag

is het mogelijk om een filmpje of een voorbeeld excelblad te maken voor de Command-Knop Om Een ​​Actief Werkblad Op Te Slaan Als PDF-Bestand Met VBA-Code.
kom er niet helemaal uit met de codes.
alvast bedankt
This comment was minimized by the moderator on the site
Hi max,
Sorry I don't understand what you mean. You may need to attach a screenshot of what you are trying to do. Sorry for the inconvenience.
This comment was minimized by the moderator on the site
Hi Team,

Just wondering if anyone could help with changing the destination of the created file to any user's desktop? My compnay doesn't allow access to C: so the script doesn't work.

MANY MANY MANY thanks!
This comment was minimized by the moderator on the site
Hi Ben Stoddart,
You just need to open any folder on your desktop and copy the folder path in the address box, then replace the folder path in the VBA code with the path you copied.
Here is the new Filename line (please replace the Username with your own username), Export.pdf is the name and the file extension of the PDF file:
Filename:="C:\Users\Username\Desktop\PDF\Export.pdf", _
This comment was minimized by the moderator on the site
Whenever I run this it saves a PDF to my local drive where the excel sheets saved, how do I stop this from auto saving?

Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
OpenAfterPublish:=True
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
When I run the below it creates a local version of the PDF automatically - how do I stop this from automatically saving?

Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
OpenAfterPublish:=True
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Hi James,
Do you want to pop up a window to select a folder to save the PDF file manually?
This comment was minimized by the moderator on the site
Hi Crystal, ideally yes so I can then choose where to save the PDF.
This comment was minimized by the moderator on the site
H James,

The following VBA code can help you solve the problem.
Note: You can't handle both the destination and the file name at the same time. After adding the following VBA code, when you click the button, a dialog box will pop up for you to select a destination folder. After selecting a destination folder, a box will pop up for you to give a name to the PDF file.

Private Sub CommandButton1_Click()
'Updated by Extendoffice 20221223
    Dim xDlg As FileDialog
    Dim xFolder As Variant
    Set xDlg = Application.FileDialog(msoFileDialogFolderPicker)
    Dim xStrName As String
    If xDlg.Show <> -1 Then Exit Sub
    
    xFolder = xDlg.SelectedItems(1)
    
    xStart = InputBox("file name", "KuTools for Excel", ActiveSheet.Name & ".pdf")

    Application.ScreenUpdating = False

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
            Filename:=xFolder & "\" & xStart, _
            OpenAfterPublish:=False
    Application.ScreenUpdating = True

End Sub
This comment was minimized by the moderator on the site
Ich nutze diese Zeilen und das funktioniert auch gut, mein Problem ist nur, sollte diese Datei bereits vorhanden sein, wird diese einfach überschrieben!
Wie kann ich das vermeiden, es sollte eine Meldung kommen, Datei existiert bereits und es soll beendet werden?
This comment was minimized by the moderator on the site
Ich nutze diese Zeilen und das funktioniert auch gut, mein Problem ist nur, sollte diese Datei bereits vorhanden sein, WIRD diese einfach überschrieben!
Wie kann ich das vermeiden, es sollte eine Meldung kommen, Datei existiert bereits und es soll beendet werden?


Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="X:\firmen\Buchhaltung\Rechnungs-Kopie_Ackermann Service GmbH\2022\RK-Abrechnung\" & ActiveSheet.Range("G1") & ".pdf", _
OpenAfterPublish:=True
Application.ScreenUpdating = True
End Sub
This comment was minimized by the moderator on the site
Hi Sascha,
The following VBA code can help. Please give it a try.

Private Sub CommandButton1_Click()
'Updated by Extendoffice 20221230
    Dim xPDFName As String
    Dim xPDFPath As String
    Dim xObjFS As Object
    Dim xNum As Integer
    Dim xStr As String
    
    xPDFName = "Export" 'The file name
    xPDFPath = "D:\work\Jan\test\" 'The file path
    Application.ScreenUpdating = True
    On Error Resume Next
    Set xObjFS = CreateObject("Scripting.FileSystemObject")
    xStr = xPDFPath & xPDFName & ".pdf"
    xNum = 1
    If xObjFS.FileExists(xStr) Then
    xResponse = MsgBox("The file already exists, do you want to overwrite it?", vbYesNo, "www.extendoffice.com", "", 0)
       If xResponse <> vbYes Then
       Exit Sub
      End If
    End If
    Application.ScreenUpdating = False
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
            FileName:=xStr, _
            OpenAfterPublish:=False
    Application.ScreenUpdating = True
End Sub
There are no comments posted here yet

Follow Us

Copyright © 2009 - www.extendoffice.com. | All rights reserved. Powered by ExtendOffice. | Sitemap
Microsoft and the Office logo are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries.
Protected by Sectigo SSL