• Skip to main content
  • Skip to header right navigation
  • Skip to site footer

My Online Training Hub

Learn Dashboards, Excel, Power BI, Power Query, Power Pivot

  • Courses
  • Pricing
    • Free Courses
    • Power BI Course
    • Excel Power Query Course
    • Power Pivot and DAX Course
    • Excel Dashboard Course
    • Excel PivotTable Course – Quick Start
    • Advanced Excel Formulas Course
    • Excel Expert Advanced Excel Training
    • Excel Tables Course
    • Excel, Word, Outlook
    • Financial Modelling Course
    • Excel PivotTable Course
    • Excel for Customer Service Professionals
    • Excel for Operations Management Course
    • Excel for Decision Making Under Uncertainty Course
    • Excel for Finance Course
    • Excel Analysis ToolPak Course
    • Multi-User Pricing
  • Resources
    • Free Downloads
    • Excel Functions Explained
    • Excel Formulas
    • Excel Add-ins
    • IF Function
      • Excel IF Statement Explained
      • Excel IF AND OR Functions
      • IF Formula Builder
    • Time & Dates in Excel
      • Excel Date & Time
      • Calculating Time in Excel
      • Excel Time Calculation Tricks
      • Excel Date and Time Formatting
    • Excel Keyboard Shortcuts
    • Excel Custom Number Format Guide
    • Pivot Tables Guide
    • VLOOKUP Guide
    • ALT Codes
    • Excel VBA & Macros
    • Excel User Forms
    • VBA String Functions
  • Members
    • Login
    • Password Reset
  • Blog
  • Excel Webinars
  • Excel Forum
    • Register as Forum Member

Convert excel worksheet to PDF?|VBA & Macros|Excel Forum|My Online Training Hub

You are here: Home / Convert excel worksheet to PDF?|VBA & Macros|Excel Forum|My Online Training Hub
Avatar
sp_LogInOut Log In sp_Registration Register
sp_Search Search
Advanced Search|Last Search Results
Search
Forum Scope




Match



Forum Options



Minimum search word length is 3 characters - maximum search word length is 84 characters
sp_Search Search
sp_RankInfo
Lost password?
sp_CrumbsHome HomeExcel ForumVBA & MacrosConvert excel worksheet to PDF?
sp_PrintTopic sp_TopicIcon
Convert excel worksheet to PDF?
Avatar
Guest
Guest
Guests
1
April 2, 2020 - 12:25 pm
sp_Permalink sp_Print

Hi,

May i know are we able to write a macro to convert excel worksheet to save as PDF format?

Thank you

sp_AnswersTopicSeeAnswer See Answer
Avatar
Purfleet
England
Member
Members


Trusted Members
Level 4
Forum Posts: 412
Member Since:
December 20, 2019
sp_UserOfflineSmall Offline
2
April 2, 2020 - 5:44 pm
sp_Permalink sp_Print

Morning

have you seen this blog post?

https://www.myonlinetraininghu.....th-outlook

The actual code to print to PDF is fairly straightforward, below is a snippet that i have used in the past (red are the parts you will might need to change based on your specific worksheet)

Sub exPDF()

Dim PDFfn, PDFLoc As String

PDFLoc = ActiveWorkbook.path & "\"

PDFfn = ActiveSheet.name & " " & Format(Now(), "DD-MMM-YYYY")

Worksheets("worksheetname").ExportAsFixedFormat _

    Type:=xlTypePDF, _

    Filename:=PDFLoc & PDFfn, _

    Quality:=xlQualityStandard, _

    openafterpublish:=False

End Sub

sp_AnswersTopicAnswer
Answers Post
Avatar
Guest
Guest
Guests
3
April 2, 2020 - 6:25 pm
sp_Permalink sp_Print

Thank you Purfleet. This is very helpful blog post. 🙂

Avatar
Guest
Guest
Guests
4
April 2, 2020 - 11:26 pm
sp_Permalink sp_Print

Hi Purfleet,

I still having problem to this macro. Why it the keep in red color & prompt me as Syntax error? I could not get the error mean. Can you help me?

Attached is the excel file.

Thank you.

Sub exPDF()

Dim PDFfn, PDFLoc As String

PDFLoc = ActiveWorkbook.Path & "\"

PDFfn = ActiveSheet.Name & " " & Format(Now(), "DD-MMM-YYYY")

Worksheets("Lead Data").ExportAsFixedFormat _

Type:=xlTypePDF,_

Filename = "C:\Users\User\Desktop\Test.pdf" & "C:\Users\User\Desktop\Test.pdf," _

Quality:=xlQualityStandard,_

openafterpublish = True

End Sub

Avatar
Purfleet
England
Member
Members


Trusted Members
Level 4
Forum Posts: 412
Member Since:
December 20, 2019
sp_UserOfflineSmall Offline
5
April 3, 2020 - 12:07 am
sp_Permalink sp_Print

It might have been a couple of issues

1) the format when pasted into the webpage then pasted back in to the VBE might not be quite right (spaces and Underscores)
2) filename didnt have a colon before the equals
3) you have put the full file location in the file name part twice
4) the comma after the file name is inside the quotes
5) not sure if the C:\Users\User\Desktop\ path is valid - i changed to my e drive in the attached

Try this one and let me know

Sub exPDF()

Worksheets("Lead data").ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:="e:\Test.pdf", _
Quality:=xlQualityStandard, _
openafterpublish:=True

End Sub

Avatar
Miguel Santos
Member
Members
Level 0
Forum Posts: 80
Member Since:
February 20, 2020
sp_UserOfflineSmall Offline
6
April 3, 2020 - 8:20 pm
sp_Permalink sp_Print

Hello,

My name is Miguel

I use the following procedures to convert my excel sheets to PDF,

I hope i can help

 

Private Sub Excel_ExportPDF()

Dim CurrentFolder As String
Dim FileName As String
Dim UniqueName As Boolean
Dim UserAnswer As VbMsgBoxResult
Dim DirFile As String

UniqueName = False

If FolderFilePDF = "Error" Then ' folder exist ?
     MsgBox "Access denied:" & Chr(10) & Chr(10) & "• Unable to locate or create destination folder!", vbCritical, "Critical error"
     Exit Sub
End If

CurrentFolder = FolderFilePDF & "\"
'FileName = "PDF file name"
FileName = Me.TextBox2.Text

Do While UniqueName = False ' File Already Exist?
     DirFile = CurrentFolder & FileName & ".pdf"
          If Len(Dir(DirFile)) <> 0 Then
               UserAnswer = MsgBox("A PDF file with that name was found:" & Chr(10) & Chr(10) & "• Do you want to replace it with this new one?.", vbQuestion + vbYesNoCancel, "Attention ")
               If CStr(UserAnswer) = CStr(False) Then Exit Sub
               If UserAnswer = vbCancel Then Exit Sub
               If UserAnswer = vbYes Then
                    UniqueName = True
                         ElseIf UserAnswer = vbNo Then
ReTry:
                         Do
                              FileName = Application.InputBox("Select new name to save the file", "Add new name to save the file", FileName, , , , , Type:=2)
                              If FileName = "" Then
                                   UniqueName = False
                                   MsgBox "Error:" & Chr(10) & Chr(10) & "• The name is invalid! No data was entered in the text box!", vbCritical, "An error has occurred"
                                   GoTo ReTry:
                              End If
                              If FileName Like "*[[/*\?!#$%&(),;:.=]*" Or FileName Like "*[]]*" Then 'do not allow invalid characters
                                   UniqueName = False
                                   MsgBox "Error:" & Chr(10) & Chr(10) & "• The name is invalid! Forbidden characters!", vbCritical, "An error has occurred"
                                   GoTo ReTry:
                              End If
                              If CStr(FileName) = CStr(False) Then Exit Sub
                         Loop While ValidFileName(FileName) = False
                              If ValidFileName(FileName) Then
                                   UniqueName = True
                                   GoTo nextStep:
                              End If
               End If
                    Else
                         UniqueName = True
          End If
Loop

nextStep:
On Error GoTo ProblemSaving:
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
FileName:=CurrentFolder & FileName & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
On Error GoTo 0

ActiveSheet.DisplayPageBreaks = False
ActiveSheet.Select

MsgBox "PDF file successfully created and saved in: " & Chr(10) & Chr(10) & "• " & CurrentFolder & Chr(10) & Chr(10) & "With the following name: " & Chr(10) & Chr(10) & "• " & FileName, vbInformation, "Successful conversion"

Exit Sub

ProblemSaving:
     MsgBox "Access denied:" & Chr(10) & Chr(10) & "• Existing PDF file open, close it and try again!", vbCritical, "Critical error"
Exit Sub

End Sub

Public Function ValidFileName(FileName As String) As Boolean ' determine if PDF file name already Exists

Dim CurrentFolder As String
Dim DirFile As String

CurrentFolder = FolderFilePDF & "\"

ValidFileName = False
'On Error GoTo InvalidFileName
DirFile = CurrentFolder & FileName & ".pdf"

If Len(Dir(DirFile)) <> 0 Then
     ValidFileName = False
          Else
               ValidFileName = True
End If

Exit Function
'InvalidFileName:
' ValidFileName = False
End Function

Public Function FolderFilePDF() As String ' determine if folder exists ? if not create one if is possible

Dim WshShell As Object
Dim fso As Object
Dim SpecialPath As String

Set WshShell = CreateObject("WScript.Shell")
Set fso = CreateObject("scripting.filesystemobject")

'SpecialPath = ThisWorkbook.path & Application.PathSeparator & "BackupPDF"
SpecialPath = ThisWorkbook.path

If Right(SpecialPath, 1) <> "\" Then
     SpecialPath = SpecialPath & "\"
End If

If fso.FolderExists(SpecialPath & "BackupPDF") = False Then
     On Error Resume Next
     MkDir SpecialPath & "BackupPDF"
     On Error GoTo 0
End If

If fso.FolderExists(SpecialPath & "BackupPDF") = True Then
     FolderFilePDF = SpecialPath & "BackupPDF"
          Else
               FolderFilePDF = "Error"
End If

End Function

Avatar
Guest
Guest
Guests
7
April 4, 2020 - 11:28 am
sp_Permalink sp_Print

Hi Purfleet,

The path that i put was correct. It can work when i put into your file. However, it doesn't  works in my file and i followed exactly the steps & code that you share with me. It still came out the compile error. 

Do you have any idea why? I noticed that if i removed the colon before the equals it not show red word but it doesn't as well. Was that due to any setting?

Error.JPGImage Enlarger

Thank you,

CY

sp_PlupAttachments Attachments
  • sp_PlupImage Error.JPG (60 KB)
Avatar
Guest
Guest
Guests
8
April 4, 2020 - 12:15 pm
sp_Permalink sp_Print

Thanks Miguel. It looks complicated to me as a beginner :). Anyway, I will try. thank you.

Avatar
Purfleet
England
Member
Members


Trusted Members
Level 4
Forum Posts: 412
Member Since:
December 20, 2019
sp_UserOfflineSmall Offline
9
April 4, 2020 - 3:59 pm
sp_Permalink sp_Print

Chiew Yen Chuah said

Hi Purfleet,

The path that i put was correct. It can work when i put into your file. However, it doesn't  works in my file and i followed exactly the steps & code that you share with me. It still came out the compile error. 

Do you have any idea why? I noticed that if i removed the colon before the equals it not show red word but it doesn't as well. Was that due to any setting?

Error.JPGImage Enlarger

Thank you,

CY  

Just a bit of formatting

1) When using the underscore to drop the code to a second line to need _ but your code was missing the space

2) There was a comma missing after the file name

Seems to work now

Convert-excel-worksheet-to-PDF_Purfleet.pngImage Enlarger

sp_PlupAttachments Attachments
  • sp_PlupImage Convert-excel-worksheet-to-PDF_Purfleet.png (3 KB)
Avatar
Guest
Guest
Guests
10
April 5, 2020 - 12:23 am
sp_Permalink sp_Print

Hi Purfleet,

oh yeahh... finally i got it!. Thank you very much Purfleet. It's really a small formatting issues make me crazy. 

Well done! 🙂 🙂

sp_Feed
Go to top
Forum Timezone: Australia/Brisbane
Most Users Ever Online: 245
Currently Online: Catalin Bombea, Velouria
Guest(s) 11
Currently Browsing this Page:
1 Guest(s)
Top Posters:
SunnyKow: 1432
Anders Sehlstedt: 871
Purfleet: 412
Frans Visser: 346
David_Ng: 306
lea cohen: 219
Jessica Stewart: 204
A.Maurizio: 202
Aye Mu: 201
jaryszek: 183
Newest Members:
Murat Hasanoglu
Brett Dryland
Saeed Aldousari
Bhuwan Devkota
Kathryn Patton
Maria Conatser
Jefferson Granemann
Glen Coulthard
Nikki Fox
Rachele Dickie
Forum Stats:
Groups: 3
Forums: 24
Topics: 6222
Posts: 27291

 

Member Stats:
Guest Posters: 49
Members: 31913
Moderators: 3
Admins: 4
Administrators: Mynda Treacy, Philip Treacy, Catalin Bombea, FT
Moderators: MOTH Support, Velouria, Riny van Eekelen
© Simple:Press —sp_Information

Sidebar

Blog Categories

  • Excel
  • Excel Charts
  • Excel Dashboard
  • Excel Formulas
  • Excel PivotTables
  • Excel Shortcuts
  • Excel VBA
  • General Tips
  • Online Training
  • Outlook
  • Power Apps
  • Power Automate
  • Power BI
  • Power Pivot
  • Power Query
microsoft mvp logo
trustpilot excellent rating
Secured by Sucuri Badge
MyOnlineTrainingHub on YouTube Mynda Treacy on Linked In Mynda Treacy on Instagram Mynda Treacy on Twitter Mynda Treacy on Pinterest MyOnlineTrainingHub on Facebook
 

Company

  • About My Online Training Hub
  • Disclosure Statement
  • Frequently Asked Questions
  • Guarantee
  • Privacy Policy
  • Terms & Conditions
  • Testimonials
  • Become an Affiliate

Support

  • Contact
  • Forum
  • Helpdesk - For Technical Issues

Copyright © 2023 · My Online Training Hub · All Rights Reserved. Microsoft and the Microsoft Office logo are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries. Product names, logos, brands, and other trademarks featured or referred to within this website are the property of their respective trademark holders.