VBA code to convert excel to pdf and email it as attachment

aarondesin91

New Member
Joined
Jun 23, 2013
Messages
7
Dear Forumers,

I really need your help. I am new to this whole VBA coding thing have no basic at all in programming and stuff so please help me out here. I am currently assigned a project where I have to create a excel sheet which act as a templete for sending request. The requirement of the project is that I need a vba code for a button when i click it, it will convert my active sheet alone to pdf, automatically save it with the title captured from a cell in the active sheet which is entered by the user. Email this pdf as a attachment to the specific person. Please help me out, my job depends on this project please guys out there.

Thank you
 
Try this:
PdfFile = PdfFile & "_" & Format(Now, "yyyyddmm_hhmmss") & ".pdf"

Please pay your attention on the fact that symbol ":" from FormatDateTime is illegal for file name



Thanks a million Vladimir!

works perfectly even with my small format change:
Code:
PdfFile = PdfFile & "_" & Format(Now, "mm.dd.yyyy_HHMM") & ".pdf"


Thanks again!
 
Upvote 0

Excel Facts

What is the last column in Excel?
Excel columns run from A to Z, AA to AZ, AAA to XFD. The last column is XFD.
I have been using this code to create a PDF file from a range. It was working for a while, right up until my company switched us to Excel 2016. The line with ".ExportAsFixedFormat..." is not working anymore. Is this something that others have run into when using Excel 2016? I have been looking for a way to get this funtion working again. Thanks.
 
Upvote 0
Hi ZVI

Using your Code on post#159, works flawlessly. Have customised pdffile name based on cell value & date. Just wondering if I cud save the pdf in a folder on desktop folder (not desktop itself). Please suggest

Thank you
 
Upvote 0
Using your Code on post#159, works flawlessly. Have customised pdffile name based on cell value & date. Just wondering if I cud save the pdf in a folder on desktop folder (not desktop itself). Please suggest
Hi,

Instead of this code line
Rich (BB code):
   PdfFile = Left(CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "\" & PdfFile, 251) & ".pdf"
Try using those lines:
Rich (BB code):
   Const MyFolder = "Test" ' Name of the Folder on Desktop
   PdfFile = Left(CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\" & MyFolder & "\" & PdfFile, 251) & ".pdf"
Notes:
1. Replace "Test" by actual name of the folder on your Desktop.
2. To not delete PDF-file don't use (just comment) this part on the bottom of the code:
Rich (BB code):
  ' Delete the temporary PDF file
  If Len(Dir(PdfFile)) Then Kill PdfFile
Regards
 
Last edited:
Upvote 0
Hi guys!

I tried to post in advanced mode but it might have failed. Therefore, if my post id duplicated, I am sorry for it and will delete the post if noe one does it before me.

This is my first post and I must say that I am impressed with the sharing here on this forum! Vladimir and the others are really nice in helping out n00bs like me. Thank you!

As others have, I used the base code from 2013 andtweaked it a bit. it all works, but the three issues that are remaining, I cannot find out and therefore need to ask for help. I was initially hoping to complete this earlier and showing it to my boss tomorrow before the weekend. My n00b skills however, thought different and I am now 4 hours overtime on my spare time to fix this. =P

Also, if I have not detected that my answers already have been given in the forum, I am sorry for reposting. I am a bit tired after 12hrs at work =/

Here are my 3 last issues:

- The attached filed to the email is the original Excel file, not the exported PDF. How can I change it to attach the exported pdf?
- After sending the email, the Kill Pdf cmd fails. Is that because the attached file is not PDF?
- The three different macro buttons underneath the form joins in on the PDF on page 2. How may I change it to only export the first page? This one I expect is tricky =/

Here is my code:


Private Sub CommandButton2_Click()
Dim IsCreated As Boolean
Dim i As Long
Dim PdfFile As String, Title As String
Dim OutlApp As Object

' Not sure for what the Title is
Title = Range("A1")

' Define PDF filename
PdfFile = ActiveWorkbook.FullName
i = InStrRev(PdfFile, ".")
If i > 1 Then PdfFile = Left(PdfFile, i - 1)
PdfFile = PdfFile & "_" & ActiveSheet.Name & ".pdf"

' Export activesheet as PDF
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\Users\Ron Holan\Desktop" & ActiveSheet.Range("C9").Value & ".pdf", Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=True
End With

' Use already open Outlook if possible
On Error Resume Next
Set OutlApp = GetObject(, "Outlook.Application")
If Err Then
Set OutlApp = CreateObject("Outlook.Application")
IsCreated = True
End If
OutlApp.Visible = True
On Error GoTo 0

' Prepare e-mail with PDF attachment
With OutlApp.CreateItem(0)

' Prepare e-mail
.Subject = "Budget offer for FRS from Bioteknikk AS"
.To = " " & ActiveSheet.Range("F10").Value & " " '
.CC = "" ' <-- Put email of 'copy to' recipient here
.Bcc = " [WORK EMAIL]" ' <-- Put email of ' blind copy to' recipient here
.Body = "Hi, " & ActiveSheet.Range("F9").Value & ", " & vbLf & vbLf _
& " " & vbLf _
& "Attached you will find our budgett offer regarding the FRS as discussed. If you have any questions, please do not hesitate to contact us. We are looking forward to cooperate with you." & vbLf & vbLf _
& "Best regards," & vbLf _
& " " & ActiveSheet.Range("D46").Value & " " & vbLf & vbLf
.Attachments.Add PdfFile

' Try to send
On Error Resume Next
.Send
Application.Visible = True
If Err Then
MsgBox "E-mail was not sent", vbExclamation
Else
MsgBox "E-mail successfully sent", vbInformation
End If
On Error GoTo 0

End With

' Delete PDF file
Kill PdfFile

' Quit Outlook if it was created by this code
If IsCreated Then OutlApp.Quit

' Release the memory of object variable
Set OutlApp = Nothing
End Sub
 
Upvote 0
Here are my 3 last issues:

1. The attached filed to the email is the original Excel file, not the exported PDF. How can I change it to attach the exported pdf?
2. After sending the email, the Kill Pdf cmd fails. Is that because the attached file is not PDF?
3. The three different macro buttons underneath the form joins in on the PDF on page 2. How may I change it to only export the first page? This one I expect is tricky =/

Hi Lilchief, Welcome to MrExcel community!

The answers to your good questions are as follows:

1. The backslash symbol should be used after the "C:\Users\Ron Holan\Desktop"
2. Kill can't delete PDF file because it's exclusively open in Adobe Viewer by OpenAfterPublish:=True, use False instead.
3. To print only page 1 use IgnorePrintAreas:=Try and From:=1, To:=1 parameters.

Below is your code with all above issues fixed:

Rich (BB code):
Private Sub CommandButton2_Click()
 
  Dim IsCreated As Boolean
  Dim i As Long
  Dim PdfFile As String
  Dim OutlApp As Object
  Dim char As Variant
 
  ' Define PDF filename
  PdfFile = Range("C9").Value
  ' Replace unallowed symbols by the underscore char
  For Each char In Split("? "" / \ < > * | :")
    PdfFile = Replace(PdfFile, char, "_")
  Next
  ' Add %TEMP% path to the file name and limit its too long pathname if happen
  PdfFile = Left(Environ("TEMP") & "\" & PdfFile, 251) & ".pdf" '
 
  ' Export an active sheet as PDF
  With ActiveSheet
    .ExportAsFixedFormat Type:=xlTypePDF, _
                         Filename:=PdfFile, _
                         Quality:=xlQualityStandard, _
                         IncludeDocProperties:=True, _
                         IgnorePrintAreas:=False, _
                         From:=1, To:=1, _
                         OpenAfterPublish:=False
  End With
 
  ' Use already open Outlook if possible
  On Error Resume Next
  Set OutlApp = GetObject(, "Outlook.Application")
  If Err Then
    Set OutlApp = CreateObject("Outlook.Application")
    IsCreated = True
  End If
  On Error GoTo 0
 
  ' Prepare e-mail with PDF attachment
  With OutlApp.CreateItem(0)
 
    ' Prepare e-mail
    .Subject = "Budget offer for FRS from Bioteknikk AS"
    .To = Range("F10").Value & " "  '
    .CC = ""                ' <-- Put email of 'copy to' recipient here
    .Bcc = "[WORK EMAIL]"  ' <-- Put email of ' blind copy to' recipient here
    .Body = "Hi, " & ActiveSheet.Range("F9").Value & ", " & vbLf & vbLf _
          & " " & vbLf _
          & "Attached you will find our budgett offer regarding the FRS as discussed. If you have any questions, please do not hesitate to contact us. We are looking forward to cooperate with you." & vbLf & vbLf _
          & "Best regards," & vbLf _
          & " " & ActiveSheet.Range("D46").Value & " " & vbLf & vbLf
    .Attachments.Add PdfFile
 
    ' Try to send
    On Error Resume Next
    .Send
    Application.Visible = True
    If Err Then
      MsgBox "E-mail was not sent", vbExclamation
    Else
      MsgBox "E-mail successfully sent", vbInformation
    End If
    On Error GoTo 0
 
  End With
 
  ' Delete PDF file
  Kill PdfFile
 
  ' Quit Outlook if it was created by this code
  If IsCreated Then OutlApp.Quit
 
  ' Release memory of the object variable
  Set OutlApp = Nothing
 
End Sub
Best Regards,
 
Last edited:
Upvote 0
Hi Vladimir! :)

Thank you for your reply this late.

I tried to do as you said, but initially it gave the same effect, unfortunately. The original Excel file is still attached (and is in a share point location and therefore wont show, but I still need it in pdf for obvious reason). I also got a bit confused if you ment "IgnorePrintAreas:=Try" or as you placed in the code "=False".

Another thing that I started wondering about, does the other two buttons have som sort of wierd relations to each other? They're all sepereated by the line and the "Private Sub Commend" / "End Sub" and I would assume they would not have any connection. Either way, Vladimir. I really appiriciate your help, I really do!

Here are the errors I got after the "normal ones" to begin with:

- Run Time error '53' and when debugged, it goes to the Kill PDF and highlights it. This is the same error I got before I posted and even though bot the "To" and "Bcc:" recipent recieves email, the PDF is not attached.
- Then I did my best to copy your code directly to mine and then I got "Runtime Error 2147024894 (80070002) - Cannot locate file. Check if file path and file name is correct".


Here is the code with your edits:

Private Sub CommandButton2_Click()

Dim IsCreated As Boolean
Dim i As Long
Dim PdfFile As String, Title As String
Dim OutlApp As Object

' Not sure for what the Title is
Title = Range("A1")

' Define PDF filename
PdfFile = ActiveWorkbook.FullName
i = InStrRev(PdfFile, ".")
If i > 1 Then PdfFile = Left(PdfFile, i - 1)
PdfFile = PdfFile & "_" & ActiveSheet.Name & ".pdf"

' Export activesheet as PDF
With ActiveSheet
.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="C:\Users\Ron Holan\Desktop" & ActiveSheet.Range("C9").Value & ".pdf", _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
From:=1, To:=1, _
OpenAfterPublish:=False
End With

' Use already open Outlook if possible
On Error Resume Next
Set OutlApp = GetObject(, "Outlook.Application")
If Err Then
Set OutlApp = CreateObject("Outlook.Application")
IsCreated = True
End If
OutlApp.Visible = True
On Error GoTo 0

' Prepare e-mail with PDF attachment
With OutlApp.CreateItem(0)

' Prepare e-mail
.Subject = "FRS Budsjettilbud fra Bioteknikk AS"
.To = " " & ActiveSheet.Range("F10").Value & " " '
.CC = "" ' <-- Put email of 'copy to' recipient here
.Bcc = "ron@bioretur.no" ' <-- Put email of ' blind copy to' recipient here
.Body = "Hi, " & ActiveSheet.Range("F9").Value & ", " & vbLf & vbLf _
& " " & vbLf _
& "Attached you will find our budgett offer regarding the FRS as discussed. If you have any questions, please do not hesitate to contact us. We are looking forward to cooperate with you." & vbLf & vbLf _
& "Best regards," & vbLf _
& " " & ActiveSheet.Range("D46").Value & " " & vbLf & vbLf
.Attachments.Add PdfFile

' Try to send
On Error Resume Next
.Send
Application.Visible = True
If Err Then
MsgBox "E-mail was not sent", vbExclamation
Else
MsgBox "E-mail successfully sent", vbInformation
End If
On Error GoTo 0

End With

' Delete PDF file
Kill PdfFile

' Quit Outlook if it was created by this code
If IsCreated Then OutlApp.Quit

' Release the memory of object variable
Set OutlApp = Nothing

End Sub
 
Upvote 0
Ny apologizing for "IgnorePrintAreas:=Try" it was my typo, I meant that "IgnorePrintAreas:=True" shouldn't be used in case the only the 1st page is expected in the PDF.

In your code this - Filename:="C:\Users\Ron Holan\Desktop" is incorrect,
should be Filename:="C:\Users\Ron Holan\Desktop\" - see my point 1 in the post #236 .

Here is the testing code, please try it and let me know details about messages and the error code line.

Rich (BB code):
Private Sub CommandButton2_Click()
 
   ' --> User settings, change to suit
  Const IsDisplay As Boolean = True           ' Change to False to .Send instead of .Display
  Const IsSilent As Boolean = False           ' Change to True to Send without the confirmation MsgBox
  ' <-- End of settings
 
  Dim IsCreated As Boolean
  Dim i As Long
  Dim PdfFile As String
  Dim OutlApp As Object
  Dim char As Variant
 
  ' Define PDF filename
  PdfFile = Range("C9").Value
  ' Check filename in C9
  If Len(Trim(PdfFile)) = 0 Then
    MsgBox "Name of PDF file is not found in C9", vbCritical, "Exit"
    Range("C9").Select
    Exit Sub
  End If
  ' Replace unallowed symbols by the underscore char
  For Each char In Split("? "" / \ < > * | :")
    PdfFile = Replace(PdfFile, char, "_")
  Next
  ' Add %TEMP% path to the file name and limit too long pathname
  PdfFile = Left(Environ("TEMP") & "\" & PdfFile, 251) & ".pdf"
 
  ' --> FOR DEBUG ONLY, Check PdfFile
  MsgBox "PdfFile will be created here: " & vbLf & PdfFile
  If Len(Dir(PdfFile)) > 0 Then
    On Error Resume Next
    Kill PdfFile
    If Err Then
      MsgBox "PDF file is already in use:" & vbLf _
           & PdfFile & vbLf _
           & "Please close all Adobe windows and try again", vbCritical, "Exit"
      Exit Sub
    End If
    On Error GoTo 0
  End If
  ' <--
 
  ' Export an active sheet as PDF
  With ActiveSheet
    .ExportAsFixedFormat Type:=xlTypePDF, _
                         Filename:=PdfFile, _
                         Quality:=xlQualityStandard, _
                         IncludeDocProperties:=True, _
                         IgnorePrintAreas:=False, _
                         From:=1, To:=1, _
                         OpenAfterPublish:=False
  End With
 
  ' --> FOR DEBUG ONLY, Check PdfFile
  If Len(Dir(PdfFile)) = 0 Then
    MsgBox "This PDF file was not created for unknown reason:" & vbLf _
          & PdfFile, vbCritical, "Exit"
    Exit Sub
  End If
  ' <--
 
  ' Use already open Outlook if possible
  On Error Resume Next
  Set OutlApp = GetObject(, "Outlook.Application")
  If Err Then
    Set OutlApp = CreateObject("Outlook.Application")
    IsCreated = True
  End If
  On Error GoTo 0
 
  ' Prepare e-mail with PDF attachment
  With OutlApp.CreateItem(0)
 
    ' Prepare e-mail
    .Subject = "Budget offer for FRS from Bioteknikk AS"
    .To = Range("F10").Value & " "  '
    .CC = ""                ' <-- Put email of 'copy to' recipient here
    .Bcc = "[WORK EMAIL]"  ' <-- Put email of ' blind copy to' recipient here
    .Body = "Hi, " & ActiveSheet.Range("F9").Value & ", " & vbLf & vbLf _
          & " " & vbLf _
          & "Attached you will find our budgett offer regarding the FRS as discussed. If you have any questions, please do not hesitate to contact us. We are looking forward to cooperate with you." & vbLf & vbLf _
          & "Best regards," & vbLf _
          & " " & ActiveSheet.Range("D46").Value & " " & vbLf & vbLf
   
     .Attachments.Add PdfFile
 
    ' Try to send or just display the e-mail
    On Error Resume Next
    If IsDisplay Then .Display Else .Send
  
    ' Show error of .Send method
    If Not IsDisplay Then
      ' Return focus to Excel's window
      Application.Visible = True
      ' Report on error or success
      If Err Then
        MsgBox "E-mail was not sent for some reasons" & vbLf & "Please check it", vbExclamation
        .Display
      Else
        If Not IsSilent Then
          MsgBox "E-mail successfully sent", vbInformation
        End If
      End If
    End If
    On Error GoTo 0
 
  End With
 
  ' Delete PDF file
  Kill PdfFile
 
  ' Quit Outlook if it was created by this code
  If IsCreated Then OutlApp.Quit
 
  ' Release memory of the object variable
  Set OutlApp = Nothing
 
End Sub
And just for the case try to save Excel file locally before running this code to exclude SharePoint influence.
What is version of your Excel?
 
Last edited:
Upvote 0
Eureka!! <3 \o/
Thank you Valdimir!! :D

Our Excel version is 2016 - with a Office365 subscription.

Nice feature to add the file path. My boss is ..wel...not a tech wonder =P I think it is nice to have until they think of it as a nuisance and want me to deactivate it. If I would deactivate it, should I delete the line:

MsgBox "PdfFile will be created here: " & vbLf & PdfFile

..since it does not have any True/False operator.

I also tried to change the file path under .ExportAsFixedFormat , but it did not like it. I need to be able to later move the file to sharepoint. Where is it possible to change the file path? It will be C:\User\User-Name\Desktop\BudgetOffer\ [FILENAME]

With your new code, I assume I could write Range("C9").Value insted of filename?
 
Upvote 0
I just reaalized, I might not need to store it on whatever computer the file is on. The file is attached to all recipents and can be downloaded from there. :confused:
 
Upvote 0

Forum statistics

Threads
1,215,045
Messages
6,122,836
Members
449,096
Latest member
Erald

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top