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
 
Hello,

I am very new to this VBA thing. Could any of you please help me with the codes to have different sheets in excel printed to PDFs and PDFs getting saved with same name as the sheet name? and then have it send through outlook to the same name ( i.e tab name). It would be a great help for me. Thankyou :)
Hi,
Does "different sheets" mean all sheets in the active workbook or some of them, or may be sheets in different workbooks?
Should all PDFs be attached to the single email or each of them have to be send separately?
 
Upvote 0

Excel Facts

Create a chart in one keystroke
Select the data and press Alt+F1 to insert a default chart. You can change the default chart to any chart type
Hi Vladimir,

Thanks for the response. I get these workbook which has close to 60 Sheets in it and each sheet has data in it. And each data (Sheet) has to go to different person through email. All the sheets in that work book is named (person name) and that is where the email needs to be sent. And all the emails would have same subject line.

So to answer your question:

Different sheets mean all sheets in active workbook

And each pdf should go to different person. Like below:

Instead of having sheet 1 Sheet 2 sheet 3.. and so on, the sheet is saved with name like John, Rudy, kayla and so on .. and the John pdf should be able to go to John vai outlook and Rudy's pdf to rudy and Kayla's to kayla email address.

Hope it makes sense. :)

Is it possible to do so?? and if it is, please could you help me on that. It will save my life. Apprecite all your help. :)

Br.
Jeson
 
Upvote 0
Hi Jason,
Yes it's possible.
Where email address should be get from for each person?
This can be of in the cell of the sheet, for example.
 
Upvote 0
This code sends each sheet as PDF file attached to email
Rich (BB code):
Sub Send_Each_Sheet_As_Pdf_With_HTMLSignature()
' ZVI:2017-02-03 http://www.mrexcel.com/forum/excel-questions/710212-visual-basic-applications-code-convert-excel-pdf-email-attachment-post4637844.html
 
  ' --> User settings, change to suit
  Const EmailCell = "C7"              ' Cell with email
  Const IsDisplay As Boolean = False  ' Change to False to .Send instead of .Display
  Const IsSilent As Boolean = True    ' Change to True to Send without the confirmation MsgBox
  ' <-- End of settings
 
  Dim IsCreated As Boolean
  Dim TempPath As String, PdfFile As String, Signature As String, Message As String
  Dim OutlApp As Object
  Dim i As Long
  Dim char As Variant
  Dim Sh As Worksheet
 
  ' Use the already open Outlook if possible
  On Error Resume Next
  Set OutlApp = GetObject(, "Outlook.Application")
  If Err Then
    ' Create new instance of Outlook aplication
    Set OutlApp = CreateObject("Outlook.Application")
    IsCreated = True
  End If
  On Error GoTo 0
 
  ' TEMP folder for PDF saving
  TempPath = CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "\"
   
  ' Turn off the screen updating
  Application.ScreenUpdating = False
 
  ' Main
  For Each Sh In ActiveWorkbook.Worksheets
   
    ' Prepare PDF file name
    Debug.Print Sh.Index, Sh.Name
    PdfFile = Sh.Name
    For Each char In Split("? "" / \ < > * | :")
      PdfFile = Replace(PdfFile, char, "_")
    Next
    PdfFile = Left(TempPath & PdfFile, 251) & ".pdf"
   
    ' Try to delete temporary PDF file
    If Len(Dir(PdfFile)) Then Kill PdfFile
   
    ' Export the selected sheets as PDF to the temporary folder
    'Sh.Select
    Sh.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
   
    ' Prepare email with PDF attachment and the default signature
    With OutlApp.CreateItem(0)
   
      ' Add the attachment first for correct attachment's name with non English symbols
      .Attachments.Add PdfFile
   
      ' Get default email signature without blinking (instead of .Display method)
      With .GetInspector: End With
      Signature = .HTMLBody
  
      ' Prepare e-mail (uncommenmt and fill the lines below)
      .Subject = "Personal Report"
      .To = Sh.Range(EmailCell).Value
      .CC = ""
      Message = "Dear " & Sh.Name & "," & vbLf & vbLf _
              & "Please find the latest report attached"
 
      .HTMLBody = Replace(Message, vbLf, Chr(60) & "br" & Chr(62)) & Signature
   
      ' 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
     
      ' Delete the temporary PDF file
      If Len(Dir(PdfFile)) Then Kill PdfFile
  
    End With
 
  Next
 
  ' Restore screen updating
  Application.ScreenUpdating = True
 
  ' Try to quit Outlook if it was not previously open
  If IsCreated Then OutlApp.Quit
 
  ' Try to release the memory of object variable
  Set OutlApp = Nothing
 
End Sub
 
Upvote 0
Thanks a bunch!!! :)

But when I use that code I am getting " Run - time error '287': Application - defined or object - defined error.

:(.
 
Upvote 0
Hope the Outlook is installed on your PC.
1. What version of MS Office are you using?
2. And which code line causes the error?
Then error message appears click on its [Debug] button - the debugger will highlight the problematic code line.
 
Last edited:
Upvote 0
Thank you for the debugging,
It means that HTML Editor is not default on your Outlook.
Then try this version of the code:
Rich (BB code):
Sub Send_Each_Sheet_As_Pdf_With_Signature()
' ZVI:2017-02-03 http://www.mrexcel.com/forum/excel-questions/710212-visual-basic-applications-code-convert-excel-pdf-email-attachment-post4637844.html
 
  ' --> User settings, change to suit
  Const EmailCell = "C7"              ' Cell with email
  Const IsDisplay As Boolean = False  ' Change to False to .Send instead of .Display
  Const IsSilent As Boolean = True    ' Change to True to Send without the confirmation MsgBox
  ' <-- End of settings
 
  Dim IsCreated As Boolean
  Dim TempPath As String, PdfFile As String, Signature As String, Message As String
  Dim OutlApp As Object
  Dim i As Long
  Dim char As Variant
  Dim Sh As Worksheet
 
  ' Use the already open Outlook if possible
  On Error Resume Next
  Set OutlApp = GetObject(, "Outlook.Application")
  If Err Then
    ' Create new instance of Outlook aplication
    Set OutlApp = CreateObject("Outlook.Application")
    IsCreated = True
  End If
  On Error GoTo 0
 
  ' TEMP folder for PDF saving
  TempPath = CreateObject("Scripting.FileSystemObject").GetSpecialFolder(2) & "\"
   
  ' Turn off the screen updating
  Application.ScreenUpdating = False
 
  ' Main
  For Each Sh In ActiveWorkbook.Worksheets
   
    ' Prepare PDF file name
    PdfFile = Sh.Name
    For Each char In Split("? "" / \ < > * | :")
      PdfFile = Replace(PdfFile, char, "_")
    Next
    PdfFile = Left(TempPath & PdfFile, 251) & ".pdf"
   
    ' Try to delete temporary PDF file
    If Len(Dir(PdfFile)) Then Kill PdfFile
   
    ' Export the selected sheets as PDF to the temporary folder
    'Sh.Select
    Sh.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PdfFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
   
    ' Prepare email with PDF attachment and the default signature
    With OutlApp.CreateItem(0)
   
      ' Add the attachment first for correct attachment's name with non English symbols
      .Attachments.Add PdfFile
   
      ' Get default email signature without blinking (instead of .Display method)
      With .GetInspector: End With
     
      Signature = .Body
  
      ' Prepare e-mail (uncommenmt and fill the lines below)
      .Subject = "Personal Report"
      .To = Sh.Range(EmailCell).Value
      .CC = ""
      Message = "Dear " & Sh.Name & "," & vbLf & vbLf _
              & "Please find the latest report attached"
 
      .Body = Message & Signature
   
      ' 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
     
      ' Delete the temporary PDF file
      If Len(Dir(PdfFile)) Then Kill PdfFile
  
    End With
 
  Next
 
  ' Restore screen updating
  Application.ScreenUpdating = True
 
  ' Try to quit Outlook if it was not previously open
  If IsCreated Then OutlApp.Quit
 
  ' Try to release the memory of object variable
  Set OutlApp = Nothing
 
End Sub
 
Upvote 0
Thanks for the updated code. :)

I tried with the new code but I could see the same line giving the error.

Below is the error:

Signature = .Body.
 
Upvote 0

Forum statistics

Threads
1,215,061
Messages
6,122,921
Members
449,094
Latest member
teemeren

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