×

VBA To Quickly Save As PDF Document From Selected Excel Worksheets

By Chris Newman •  Updated: 03/24/16 •  7 min read
VBA To Quickly Save As PDF Document From Selected Excel Worksheets

What This VBA Macro Code Does

The business world has increasingly become more reliant on mobile computing with devices such as tablets and smartphones becoming mainstream. This, in turn, has provided an elevated demand for analysts to turn spreadsheets into PDF documents so management can view your reports on the go. 

Below is a simple VBA macro that will allow you to quickly turn your selected worksheet(s) into a PDF file in a snap. The code is written to save your document in the same folder as the Excel file currently resides. If you need to make modifications, hopefully, you will be able to follow along with my code comments and customize the code to your specific needs.

Sub Excel_ExportPDF()
'PURPOSE: Generate A PDF Document With Selected Worksheet(s)
'NOTES: PDF Will Be Saved To Same Folder As Excel File
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim CurrentFolder As String
Dim FileName As String
Dim myPath As String
Dim UniqueName As Boolean

UniqueName = False

'Store Information About Excel File
  myPath = ActiveWorkbook.FullName
  CurrentFolder = ActiveWorkbook.Path & "\"
  FileName = Mid(myPath, InStrRev(myPath, "\") + 1, _
   InStrRev(myPath, ".") - InStrRev(myPath, "\") - 1)

'Does File Already Exist?
  Do While UniqueName = False
    DirFile = CurrentFolder & FileName & ".pdf"
    
    If Len(Dir(DirFile)) <> 0 Then
      UserAnswer = MsgBox("File Already Exists! Click " & _
       "[Yes] to override. Click [No] to Rename.", vbYesNoCancel)
      
      If UserAnswer = vbYes Then
        UniqueName = True
      ElseIf UserAnswer = vbNo Then
        Do
          'Retrieve New File Name
            FileName = Application.InputBox("Provide New File Name " & _
             "(will ask again if you provide an invalid file name)", , _
             FileName, Type:=2)
            
          'Exit if User Wants To
            If FileName = "False" Or FileName = "" Then Exit Sub
        Loop While ValidFileName(FileName) = False
      Else
        Exit Sub 'Cancel
      End If
    Else
      UniqueName = True
    End If
  Loop
  
'Save As PDF Document
  On Error GoTo ProblemSaving
    ActiveSheet.ExportAsFixedFormat _
      Type:=xlTypePDF, _
      FileName:=CurrentFolder & FileName & ".pdf", _
      Quality:=xlQualityStandard, _
      IncludeDocProperties:=True, _
      IgnorePrintAreas:=False, _
      OpenAfterPublish:=False
  On Error GoTo 0

'Disable Page Breaks
  ActiveSheet.DisplayPageBreaks = False
  ActiveSheet.Select

'Confirm Save To User
  With ActiveWorkbook
    FolderName = Mid(.Path, InStrRev(.Path, "\") + 1, Len(.Path) - InStrRev(.Path, "\"))
  End With
  
  MsgBox "PDF Saved in the Folder: " & FolderName

Exit Sub

'Error Handlers
ProblemSaving:
  MsgBox "There was a problem saving your PDF. This is most commonly" & _
   " caused by the original PDF file already being open."
  Exit Sub

End Sub

Function To Validate Save File Name

Below is a function that you will need to paste in along with the above macro. The VBA function provides a way of testing any file name your users provide to save the PDF document as.

Function ValidFileName(FileName As String) As Boolean
'PURPOSE: Determine If A Given Excel File Name Is Valid
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim TempPath As String
Dim wb As Workbook

'Determine Folder Where Temporary Files Are Stored
  TempPath = Environ("TEMP")

'Create a Temporary XLS file (XLS in case there are macros)
  On Error GoTo InvalidFileName
    Set wb = ActiveWorkbook.SaveAs(ActiveWorkbook.TempPath & _
     "\" & FileName & ".xls", xlExcel8)
  On Error Resume Next

'Delete Temp File
  Kill wb.FullName

'File Name is Valid
  ValidFileName = True

Exit Function

'ERROR HANDLERS
InvalidFileName:
  'File Name is Invalid
    ValidFileName = False

End Function

Same Macro Functionality For Other Office Applications

Upon request, I have made similar macros for other Office Applications you may use on a regular basis to convert their files into PDF documents. The links to those specific posts are as follows:

Microsoft PowerPoint Version

Microsoft Word Version

Using VBA Code Found On The Internet

Now that you’ve found some VBA code that could potentially solve your Excel automation problem, what do you do with it? If you don’t necessarily want to learn how to code VBA and are just looking for the fastest way to implement this code into your spreadsheet, I wrote an article (with video) that explains how to get the VBA code you’ve found running on your spreadsheet.

Getting Started Automating Excel

Are you new to VBA and not sure where to begin? Check out my quickstart guide to learning VBA. This article won’t overwhelm you with fancy coding jargon, as it provides you with a simplistic and straightforward approach to the basic things I wish I knew when trying to teach myself how to automate tasks in Excel with VBA Macros.

Also, if you haven’t checked out Excel’s latest automation feature called Power Query, I have put together a beginner’s guide for automating with Excel’s Power Query feature as well! This little-known built-in Excel feature allows you to merge and clean data automatically with little to no coding!

How Do I Modify This To Fit My Specific Needs?

Chances are this post did not give you the exact answer you were looking for. We all have different situations and it’s impossible to account for every particular need one might have. That’s why I want to share with you: My Guide to Getting the Solution to your Problems FAST! In this article, I explain the best strategies I have come up with over the years to get quick answers to complex problems in Excel, PowerPoint, VBA, you name it

I highly recommend that you check this guide out before asking me or anyone else in the comments section to solve your specific problem. I can guarantee that 9 times out of 10, one of my strategies will get you the answer(s) you are needing faster than it will take me to get back to you with a possible solution. I try my best to help everyone out, but sometimes I don’t have time to fit everyone’s questions in (there never seem to be quite enough hours in the day!).

I wish you the best of luck and I hope this tutorial gets you heading in the right direction!

Keep Learning

Chris Newman

Chris Newman

Chris is a finance professional and Excel MVP recognized by Microsoft since 2016. With his expertise, he founded TheSpreadsheetGuru blog to help fellow Excel users, where he shares his vast creative solutions & expertise. In addition, he has developed over 7 widely-used Excel Add-ins that have been embraced by individuals and companies worldwide.

[FREE Training] 10 Amazing Excel Efficiency Tricks. Why Don't People Know These?!

X