Forum

Convert excel works...
 
Notifications
Clear all

Convert excel worksheet to PDF?

10 Posts
3 Users
0 Reactions
275 Views
(@Anonymous)
Posts: 0
New Member Guest
 

Hi,

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

Thank you

 
Posted : 02/04/2020 10:25 pm
(@purfleet)
Posts: 412
Reputable Member
 

Morning

have you seen this blog post?

https://www.myonlinetraininghub.com/vba-to-create-pdf-from-excel-worksheet-then-email-it-with-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

 
Posted : 03/04/2020 3:44 am
(@Anonymous)
Posts: 0
New Member Guest
 

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

 
Posted : 03/04/2020 4:25 am
(@Anonymous)
Posts: 0
New Member Guest
 

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:UsersUserDesktopTest.pdf" & "C:UsersUserDesktopTest.pdf," _

Quality:=xlQualityStandard,_

openafterpublish = True

End Sub

 
Posted : 03/04/2020 9:26 am
(@purfleet)
Posts: 412
Reputable Member
 

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:UsersUserDesktop 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

 
Posted : 03/04/2020 10:07 am
(@rhysand)
Posts: 80
Trusted Member
 

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

 
Posted : 04/04/2020 6:20 am
(@Anonymous)
Posts: 0
New Member Guest
 

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.JPG

Thank you,

CY

 
Posted : 04/04/2020 9:28 pm
(@Anonymous)
Posts: 0
New Member Guest
 

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

 
Posted : 04/04/2020 10:15 pm
(@purfleet)
Posts: 412
Reputable Member
 

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.JPG

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.png

 
Posted : 05/04/2020 1:59 am
(@Anonymous)
Posts: 0
New Member Guest
 

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! 🙂 🙂

 
Posted : 05/04/2020 10:23 am
Share: