Attach both pdf and excel files to an email on single click in VBA - vba

I have VBA code to create pdf file in excel and attache to email on button click. i am wondering if it is possible to attach both pdf and excel file to an email on single click.
please find below code which i am trying to modify.. bold section showing two functions. any suggestion or help greatly appreciated !! Thanks
Sub Button1_Click()
Dim EmailSubject As String, EmailSignature As String
Dim Email_Body As String
Dim olMailItem As Object
'Dim olFormatHTML As Form
Dim objMail As Object
Dim CurrentMonth As String, DestFolder As String, PDFFile As String
Dim Email_To As String, Email_CC As String, Email_BCC As String
Dim OpenPDFAfterCreating As Boolean, AlwaysOverwritePDF As Boolean, DisplayEmail As Boolean
Dim OverwritePDF As VbMsgBoxResult
Dim OutlookApp As Object, OutlookMail As Object
'CurrentMonth = ""
Dim fName As String, eCode1 As String, eCode2 As String, fNameLong As String
' *****************************************************
' ***** You Can Change These Variables *********
'Create excel
fName = "User Access request:"
eCode1 = Sheet1.Range("B7").Value
eCode2 = Range("B7").Value
fNameLong = fName & " " & eCode1 & " - " & eCode2
EmailSubject = "abs" 'Change this to change the subject of the email. The current month is added to end of subj line
OpenPDFAfterCreating = False 'Change this if you want to open the PDF after creating it : TRUE or FALSE
AlwaysOverwritePDF = True 'Change this if you always want to overwrite a PDF that already exists :TRUE or FALSE
DisplayEmail = True 'Change this if you don't want to display the email before sending. Note, you must have a TO email address specified for this to work
Email_To = "abc" 'Change this if you want to specify To email e.g. ActiveSheet.Range("H1") to get email from cell H1
Email_CC = "xyz.com"
Email_BCC = ""
'Create the PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=PDFFile, Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas _
:=False, OpenAfterPublish:=OpenPDFAfterCreating
**
'Create an Outlook object and new mail message
Set OutlookApp = CreateObject("Outlook.application") 'Dialogs (DialogSendMail).Show ")
Set OutlookMail = OutlookApp.CreateItem(0)
'Create excel file but to another email
Application.Dialogs(xlDialogSendMail).Show "xyz", fNameLong
**
'Display email and specify To, Subject, etc
With OutlookMail
.Display
.To = Email_To
.Cc = Email_CC
.BCC = Email_BCC
.Subject = EmailSubject & CurrentMonth
.Attachments.Add PDFFile
If DisplayEmail = False Then
.Send
End If
End With
End Sub

With OutlookMail
.Display
.To = Email_To
.Cc = Email_CC
.BCC = Email_BCC
.Subject = EmailSubject & CurrentMonth
.Attachments.Add PDFFile
.Attachments.Add "[Excel File Path Goes Here]" 'Add this line
If DisplayEmail = False Then
.Send
End If
End With

Related

How to: attach .pdf and send email with no user input needed

I've edited my question based on the feedback. I have a form that I want users to be able to silently (no user input required) save and send with one button click.
The following code is saving as a .pdf with the correct name in the same document/path as the original file (which I want). However when the email is sent, the attachment is the original .docm file instead.
The final attachment must be a .pdf as it will be emailed to a Microsoft Team site and macro-enabled files will not work on Teams.
I'm new to VBA beyond basic commands for my own workflow. I'm working my way through various tutorials/courses and an extremely large book on vba for Office but I would appreciate a fix my newbie coding error sooner rather than later.
Private Sub btnSubmit_Click()
strName = ActiveDocument.SelectContentControlsByTitle("ddName")(1).Range.Text
strDate = ActiveDocument.SelectContentControlsByTitle("ddDate")(1).Range.Text
strTest = ActiveDocument.SelectContentControlsByTitle("ddTestNumber")(1).Range.Text
Dim strFilename As String
strFilename = strName & "_" & "VBATestFile_" & strTest & "_" & Format(strDate, "yyyymmdd") & ".pdf"
ActiveDocument.SaveAs2 strFilename, FileFormat:=wdFormatPDF
Dim OL As Object
Dim EmailItem As Object
Dim Doc As Document
Application.ScreenUpdating = False
Set OL = CreateObject("Outlook.Application")
Set EmailItem = OL.CreateItem(olMailItem)
Set Doc = ActiveDocument
Doc.Save
With EmailItem
.Subject = strName & " Test" & strTest
.Body = "Test email send for " & strName & " " & strTest & "."
.To = "email address here"
.Importance = olImportanceNormal
.Attachments.Add Doc.FullName
.Send
End With
Application.ScreenUpdating = True
MsgBox "Form Submitted", vbInformation
Set Doc = Nothing
Set OL = Nothing
Set EmailItem = Nothing
End Sub
Solved:
Private Sub btnSubmit_Click()
strName = ActiveDocument.SelectContentControlsByTitle("ddName")(1).Range.Text
strDate = ActiveDocument.SelectContentControlsByTitle("ddDate")(1).Range.Text
strTest = ActiveDocument.SelectContentControlsByTitle("ddTestNumber")(1).Range.Text
Dim strFilename As String 'Create Filename based on data in Content Controls
strFilename = strName & "_" & "VBATestFile_" & strTest & "_" & format(strDate, "yyyymmdd") & ".pdf"
ActiveDocument.SaveAs2 strFilename, FileFormat:=wdFormatPDF 'Save as .pdf to Documents folder
Dim OL As Object
Dim EmailItem As Object
Dim Doc As Document
Dim sPathUser As String 'Get current file path
sPathUser = Environ$("USERPROFILE") & "\my documents\"
Application.ScreenUpdating = False 'Silently send email with .pdf file attached
Set OL = CreateObject("Outlook.Application")
Set EmailItem = OL.CreateItem(olMailItem)
Set Doc = ActiveDocument
Doc.Save
With EmailItem
.Subject = strName & " Test " & strTest
.Body = "Test email send for " & strName & " " & strTest & "."
.To = "email address"
.Importance = olImportanceNormal
.Attachments.Add strFilename
.Send
End With
Application.ScreenUpdating = True
MsgBox "Form Submitted", vbInformation 'Confirm document submission for user
Set Doc = Nothing
Set OL = Nothing
Set EmailItem = Nothing
End Sub

How to attach created .pdf to email body with VBA

I have a converted document from .docx into .pdf saved to the desktop. The last task is to attach this .pdf to the body of an e-mail; the HTML signature should remain unchanged.
I think the problem is this line of code and I don't know how to correct it:
.Attachments.Add PdfFile.FullName
The complete code:
Public Sub Mail()
Dim LastAuthor As String
LastAuthor = ActiveDocument.BuiltInDocumentProperties("last Author")
Dim Email As String
Email = Replace(LastAuthor, " ", ".") & "#xyz.ro"
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.Display
.Signature = "HTMLbody"
.To = Email
.CC = ""
.BCC = ""
.Subject = ActiveDocument.Name
'.Body = "AVIZAT. Multumesc mult"
'.Attachments.Add ActiveDocument.FullName
' You can add other files by uncommenting the following line.
'.Attachments.Add ("C:\test.txt")
' In place of the following statement, you can use ".Display" to
' display the mail.
.HTMLbody = "AVIZAT, esantionul este in ordine. Multumesc" & "<br>" & .HTMLbody
Dim objDoc As Document
Set objDoc = ActiveDocument
objDoc.ExportAsFixedFormat _
OutputFileName:=Replace(objDoc.FullName, ".docx", ".pdf"), _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, Item:=wdExportDocumentContent
' Add the attachment first for correct attachment's name with non English symbols
.Attachments.Add PdfFile.FullName
'.Preview 'Preview the email must disable .send & MsgBox (or use .Send to send it)
.send
MsgBox "E-mail trimis cu succes"
Set OutMail = Nothing
Set OutApp = Nothing
End With
End Sub
This will do:
Public Sub Mail()
Dim LastAuthor As String
Dim Email As String
Dim MyPdfName As String
Dim objDoc As Document
LastAuthor = ActiveDocument.BuiltinDocumentProperties("last Author")
Email = Replace(LastAuthor, " ", ".") & "#xyz.ro"
Set objDoc = ActiveDocument
MyPdfName = Replace(objDoc.FullName, ".docx", ".pdf")
objDoc.ExportAsFixedFormat _
OutputFileName:=MyPdfName, _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, _
Range:=wdExportAllDocument, Item:=wdExportDocumentContent
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.Display
.To = Email
.CC = ""
.BCC = ""
.Subject = objDoc.Name
.HTMLBody = "<BODY style=font-size:12pt;font-family:Calibri>Servus<br>Esantionul este in ordine.<br><br>Multumesc,<br>" & .HTMLBody
.Attachments.Add MyPdfName
.Send
End With
Set OutMail = Nothing
Set OutApp = Nothing
MsgBox "E-mail trimis cu succes"
End Sub
It's far from perfect but is a lot clearer now and most importantly, works.

Multi-line email body when sending emails from excel

I am trying to automate sending emails with multiple lines and paragraphs through excel using VBA. Here is the code I have so far:
Sub Send_Email()
Dim Email_Subject, Email_Send_From, Email_Send_To, _
Email_Cc, Email_Bcc, Email_Body As String
Dim Mail_Object, Mail_Single As Variant
Email_Subject = "test"
Email_Send_From = "email"
Email_Cc = ""
Email_Bcc = ""
Dim r As Range, cell As Range, mynumber As Long
Dim i As Long
Set r = Range("K2:K300")
i = 2
For Each cell In r
If Cells(i, "K").Value = "" Then
Else
Email_Send_To = Worksheets("Sheet1").Cells(i,"K").Value
Email_Body = "test from outlook excel"
Set Mail_Object = CreateObject("Outlook.Application")
Set Mail_Single = Mail_Object.CreateItem(0)
With Mail_Single
.Subject = Email_Subject
.To = Email_Send_To
.cc = Email_Cc
.BCC = Email_Bcc
.Body = Email_Body
.send
End With
End If
i = i + 1
Next
On Error GoTo debugs
debugs:
If Err.Description <> "" Then MsgBox Err.Description
End Sub
However I'm not sure how to make the body of the email include line breaks and split up paragraphs rather than just having one block of text.
Use VBNewLine for a new line character.
Dim A As String: A = "Line A"
Dim B As String: B = "Line B"
Debug.print(A & VbNewLine & B)
Output:
Line A
Line B

Sending two PDFs by email

I made the code (as shown below) which send one PDF by email correctly, but I need to send one more PDF.
Dim varFindThis As Variant
Dim rngLookIn As Range
varFindThis = Worksheets("Suivi").Range("B1")
Set rngLookIn = Worksheets("Suivi").Range("A:A")
If Not rngLookIn.Find(varFindThis, LookIn:=xlValues) Is Nothing Then
Dim f As String
f = Worksheets("Suivi").Range("B1").Value
'Since i didn't got that clear, here above you must create a code to declare "f" as whatever you want
Set c = Worksheets("Suivi").Range("A:A").Find(f)
Worksheets("Suivi").Range(c.Address).EntireRow.Delete
End If
'Do not forget to change the email ID
'before running this code
Dim OlApp As Object
Dim NewMail As Object
Dim TempFilePath As String
Dim TempFileName As String
Dim FileFullPath As String
' With Application
' .ScreenUpdating = False
' .EnableEvents = False
' End With
Application.DisplayFullScreen = False
ThisWorkbook.Worksheets("PDF").Activate
Range("B1:BG46").Select
ActiveSheet.PageSetup.PrintArea = "$B$1:$BG$46"
' Temporary file path where pdf
' file will be saved before
' sending it in email by attaching it.
TempFilePath = Environ$("temp") & "\"
' Now append a date and time stamp
' in your pdf file name. Naming convention
' can be changed based on your requirement.
TempFileName = ActiveSheet.Name & "-" & Format(Now, "dd-mmm-20yy") & ".pdf"
'Complete path of the file where it is saved
FileFullPath = TempFilePath & TempFileName
'Now Export the Activesshet as PDF with the given File Name and path
On Error GoTo err
With ActiveSheet
.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=FileFullPath, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End With
'Now open a new mail
Set OlApp = CreateObject("Outlook.Application")
'Loop through the rows
For Each cell In ThisWorkbook.Sheets("Envoie").Columns("C").Cells.SpecialCells(xlCellTypeVisible)
If cell.Value Like "*#*" Then
EmailAddr1 = EmailAddr1 & ";" & cell.Value
End If
Next
For Each cell In ThisWorkbook.Sheets("Envoie").Columns("G").Cells.SpecialCells(xlCellTypeVisible)
If cell.Value Like "*#*" Then
EmailAddr2 = EmailAddr2 & ";" & cell.Value
End If
Next
Subj = "N°Article" & ThisWorkbook.Sheets("CalculInfo").Range("A10")
Set NewMail = OlApp.CreateItem(0)
On Error Resume Next
With NewMail
.To = EmailAddr1
.CC = EmailAddr2
.BCC = "gaetan.affolter#he-arc.ch"
.Subject = Subj
.Body = "Bonjour, il vous reste 24 heures pour vérifier les données du PDF et de confirmer dans Octopus. Merci"
.Attachments.Add FileFullPath '--- full path of the pdf where it is saved
.Send 'or use .Display to show you the email before sending it.
End With
On Error GoTo 0
'Since mail has been sent with the attachment
'Now delete the pdf file from the temp folder
Kill FileFullPath
'set nothing to the objects created
Set NewMail = Nothing
Set OlApp = Nothing
'Now set the application properties back to true
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
MsgBox ("Email a été envoyé")
Exit Sub
err:
MsgBox err.Description
Unload Me
The PrintArea I situated in the Worksheets("CalcGammeControle") and more precisely in "$G$2:$G$35"
How can I add it?

Saving Excel file as PDF then send by Outlook as Attachment but no signature in the messge

I have some Excel VBA code which save active sheet as PDF then attach that PDF file to outlook new mail everything works fine except the signature in outlook when the code starts outlook and new message it does not show the signature despite its in HTML and I can already insert it manually.
so any adjustment to the code will be appreciated.
Sub Send_To_Pdf()
Dim PdfPath As String
Dim BoDy As String
BoDy = Msg = "Dear Mr. " & vbCrLf & vbCrLf & "Good Day" & vbCrLf & vbCrLf & "Kindly find the attahched P.O to be delivered to " & Cells(10, 12)
PdfPath = Save_as_pdf
EnvoiMail Right(PdfPath, InStr(1, StrReverse(PdfPath), "\") - 1), "recepient1#domain.com;recepient2#domain.com", , , BoDy, 1, PdfPath
End Sub
Public Function Save_as_pdf() As String
Dim FSO As Object
Dim s(1) As String
Dim sNewFilePath As String
Set FSO = CreateObject("Scripting.FileSystemObject")
s(0) = "C:\Users\" & Environ("UserName") & "\Desktop\" & ThisWorkbook.Name
If FSO.FileExists(ThisWorkbook.FullName) Then
'//Change Excel Extension to PDF extension in FilePath
s(1) = FSO.GetExtensionName(s(0))
If s(1) <> "" Then
s(1) = "." & s(1)
sNewFilePath = Replace(s(0), s(1), ".pdf")
'//Export to PDF with new File Path
ActiveSheet.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=sNewFilePath, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Else
'//Error: file path not found
MsgBox "Error: this workbook may be unsaved. Please save and try again."
End If
Set FSO = Nothing
Save_as_pdf = sNewFilePath
End Function
Sub EnvoiMail(Subject As String, Destina As String, Optional CCdest As String, Optional CCIdest As String, Optional BoDyTxt As String, Optional NbPJ As Integer, Optional PjPaths As String)
Dim MonOutlook As Object
Dim MonMessage As Object
Set MonOutlook = CreateObject("Outlook.Application")
Set MonMessage = MonOutlook.createitem(0)
Dim PJ() As String
PJ() = Split(PjPaths, ";")
With MonMessage
.Subject = Subject '"Je suis content"
.To = Destina '"marcel#machin.com;julien#chose.com"
.cc = CCdest '"chef#machin.com;directeur#chose.com"
.bcc = CCIdest '"un.copain#supermail.com;une-amie#hotmail.com"
.BoDy = BoDyTxt
If PjPaths <> "" And NbPJ <> 0 Then
For i = 0 To NbPJ - 1
'MsgBox PJ(I)
.Attachments.Add PJ(i) '"C:\Mes Documents\Zoulie Image.gif"
Next i
End If
.display
'.send '.Attachments.Add ActiveWorkbook.FullName
End With '?plusieurs?MonMessage.Attachments.Add "D:\Prof\Janvier\Base clients.mdb"
Set MonOutlook = Nothing
End Sub
After a new message is created you need to insert a new text before the default signature (not to overwrite it), for example:
.BoDy = BoDyTxt
The default signature will be erased in that case.
.Body = BoDyTxt & .Body
In that case the text will be inserted in the beginning of the message leaving the signature as is.
The Outlook object model provides three different ways for working with item bodies:
Body - a plain text.
HTMLBody - an HTML markup.
The Word Editor. Outlook uses Word as an email editor, so you can use it to format the email message. The WordEditor property of the Inspector class returns an instance of the Document class which represents the message body.
You can read more about all these ways in the Chapter 17: Working with Item Bodies in MSDN.
thanks Eugene Astafiev
i changed some of the code and i got it worked after all
the changed part is as following:
Sub EnvoiMail(Subject As String, Destina As String, Optional CCdest As String, Optional CCIdest As String, Optional BoDyTxt As String, Optional NbPJ As Integer, Optional PjPaths As String)
Dim MonOutlook As Object
Dim MonMessage As Object
Dim strbody As String 'i added this part <<>>>'
Set MonOutlook = CreateObject("Outlook.Application")
Set MonMessage = MonOutlook.CreateItem(0)
strbody = "Hello" ' i put my messages here as well which i change it in my main code to get values from cells <<<<>>>'
Dim PJ() As String
PJ() = Split(PjPaths, ";")
With MonMessage
.Display ' <<<<< the most important part of the code which solved 50% of the problem >>>>'
.Subject = Subject
.To = Destina
.CC = CCdest
.BCC = CCIdest
.HTMLBoDy = strbody & "<br>" & .HTMLBoDy ' <<<< the second import part of the code and solved the other 50% >>>>> '
If PjPaths <> "" And NbPJ <> 0 Then
For i = 0 To NbPJ - 1
'MsgBox PJ(I)
.Attachments.Add PJ(i)
Next i
End If
.Display
'.send
End With
Set MonOutlook = Nothing
End Sub