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

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

Related

How to assign a recipient to .To?

I convert a worksheet into a PDF and am trying to have that PDF emailed to me and copied to another person. All of this will be assigned to an action button/trigger.
Option Explicit
Sub SendExcelFileAsPDF()
Dim OutlookApp As Outlook.Application
Dim emItem As Object
Dim Receipt As String, Subject As String
Dim Message As String, Fname As String
Dim Recipient As Outlook.Recipient
Recipient = "xxxxx.xxxxx#fedex.com"
Subject = "Weekly Critical Items" & " " & Range("L1")
Message = Range("D2") & Range("J2") & "Weekly Critical Items submitted" &
Range("L1") & " " & "in PDF Format"
Message = Message & vbNewLine & vbNewLine & "Offload Ops"
Fname = Application.DefaultFilePath & "/" & ActiveWorkbook.Name & ".pdf"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=Fname
Set OutlookApp = New Outlook.Application
Set emItem = OutlookApp.CreateItem(olMailItem)
With emItem
.To = Recipient = "xxxxx.xxxxx#fedex.com"
.Subject = Subject
.Body = Message
.Attachements.Add Fname
.Send
End With
Set OutlookApp = Nothing
End Sub
The recipient line is where I am having issues. When I run the debugger, it's giving
Run-Time error '91: Object variable or with block variable not set
I would dim recipient as string and update the .to assignment:
Change
Dim Recipient As Outlook.Recipient
.To = Recipient = "dennis.aikens#fedex.com"
to
Dim Recipient As string
.To = Recipient
This line
.To = Recipient = "dennis.aikens#fedex.com"
Should be just
.To = Recipient

VBA Kill function not deleting file

I have written VBA code for Microsoft Word to send an email when a button is clicked. When the button is clicked, and the macro is completed, I would like the file to be deleted from the Desktop.
When I run this macro now, Microsoft Word closes out, but the file is not deleted from my desktop.
Here is my code:
Private Sub CommandButton1_Click()
Dim OL As Object
Dim EmailItem As Object
Dim Doc As Document
Dim FileName As String
Dim FilePath As String
Dim DeletePath As String
Application.ScreenUpdating = False
Set OL = CreateObject("Outlook.Application")
Set EmailItem = OL.CreateItem(olMailItem)
Set Doc = ActiveDocument
myFileName = "Form"
FilePath = "C:\Users\" & Environ("Username") & "\desktop\"
Doc.SaveAs2 FileName:=FilePath & myFileName & ".docx", Fileformat:=wdFormatXMLDocument, AddToRecentFiles:=False
With EmailItem
.Subject = "Bid Award Form"
.Body = "Please Review the attached Bid Award form"
.To = "EMAILADDRESS#DOMAIN.COM"
.Importance = olImportanceNormal 'Or olImprotanceHigh Or olImprotanceLow
.Attachments.Add Doc.FullName
.Send
End With
'display a message using named arguments
MsgBox _
prompt:="Your email has been sent. Please check your Outlook sent mail for confirmation", _
Buttons:=vbOKOnly, _
Title:="Email Confirmation"
'Close the File
Doc.Close
Kill "C:\Users\" & Environ("Username") & "\desktop\form.docx"
'Close the Application of the document we are going to delete
Application.Quit
Application.ScreenUpdating = True
Set Doc = Nothing
Set OL = Nothing
Set EmailItem = Nothing
End Sub
Any help that you can provide will be very helpful!
Probably you are looking at the wrong file. Kill is a function, that makes no mistakes.
Simply try the following:
Sub KillTheFile
Kill "C:\Users\" & Environ("Username") & "\desktop\form.docx"
End Sub
Then see if it works. Probably you are having a file frm.docx or similar.
Try it like this instead
On Error Goto 0
Dim sDocName as string
sDocName = Doc.FullName
Doc.Close
Kill sDocName

Convert word doc to pdf and send as attachment in Outlook

I would like to convert my Word Doc to a pdf and send it as an attachment as part of my constructed Outlook email.
I have tried adding ,".pdf" at the end of my SaveAs2 line, which changed and attached the file format as pdf, however, when attempting to open the file it does not display and gives me a message that the file did not have all it's code when sent as an attachment.
Private Sub emailbutton_Click()
'No-option email sending
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
If VName.Value = "" Then
Doc.SaveAs ("Quotation_Blank 2016")
Else
Doc.SaveAs2 ("QFORM" & "_" & JNumber.Value & "_" & VName.Value)
End If
With EmailItem
.Display
End With
' Signature = EmailItem.body
With EmailItem
.Subject = "QFORM" & "_" & JNumber.Value & "_" & VName.Value
'HTMLbody
msg = "<b><font face=""Times New Roman"" size=""4"" color=""blue"">INTEGRATED ASSEMBLY </font></b><br>" _
& " 1200 Woodruff Rd.<br>" _
& " Suite A12<br>" _
& " Greenville, SC 29607<br><br>" _
& "We have recently released subject project, which will contain assemblies to be outsourced. You have been selected to build these assemblies according to the attachment. <br><br>" _
& "As part of this process, please review the quotation form attached and indicate your acceptance. If adjustments and-or corrections are required, please feel free to contact us for quick resolution. <br><br>" _
& "<b><font face=""Times New Roman"" size=""4"" color=""Red"">NOTE: </font></b>" _
& "The information on attached quotation form is not a contract and only an estimate of predetermined costs per hourly rate for outsource assemblies. <br><br>" _
& "*******For your records you may wish to print out the completed quote form. <br><br>" _
& "Thank you, <br><br>" _
& "<b>HARTNESS INTERNATIONAL </b><br>" _
& "H1 Production Control <br>" _
& vbNewLine & Signature
.HTMLBody = msg & .HTMLBody
If VName.Value = "INTEGRATED ASSEMBLY" Then
.To = "Email1.com;"
.CC = "Email2.com;" & "Email3.com;"
.Importance = olImportanceNormal 'Or olImportanceHigh Or olImportanceLow
.Attachments.Add Doc.FullName
.Display
ElseIf VName.Value = "LEWALLEN" Then
.To = "Email1.com;"
.CC = "Email2.com;" & "Email3.com;"
.Importance = olImportanceNormal 'Or olImportanceHigh Or olImportanceLow
.Attachments.Add Doc.FullName
.Display
End If
End With
Application.ScreenUpdating = True
Set Doc = Nothing
Set OL = Nothing
Set EmailItem = Nothing
End Sub
With SaveAs2 you can specify FileFormat
https://msdn.microsoft.com/en-us/library/office/ff836084.aspx
expression .SaveAs2(FileName, FileFormat, LockComments, Password, AddToRecentFiles, WritePassword, ReadOnlyRecommended, EmbedTrueTypeFonts, SaveNativePictureFormat, SaveFormsData, SaveAsAOCELetter, Encoding, InsertLineBreaks, AllowSubstitutions, LineEnding, AddBiDiMarks, CompatibilityMode)
https://msdn.microsoft.com/en-us/library/office/ff839952.aspx
FileFormat is wdFormatPDF or 17
Change your saveAs2 this way.
If VName.Value = "" Then
Doc.SaveAs ("Quotation_Blank 2016")
Else
Doc.ExportAsFixedFormat OutputFileName:="QFORM" & "_" & JNumber.Value , _
ExportFormat:=wdExportFormatPDF
End If
Edit
To use path & add is as attachment
If VName.Value = "" Then
Doc.SaveAs ("Quotation_Blank 2016")
Else
Path = "C:\Temp\"
FileName = "QFORM" & "_" & JNumber.Value & "_" & VName.Value
Doc.ExportAsFixedFormat OutputFileName:=Path & FileName, _
ExportFormat:=wdExportFormatPDF
End If
And Attahcment
.Attachments.Add Path & FileName & ".pdf"
If you need to convert multiple Word files to other formats, like TXT, RTF, HTML or PDF, run the script below.
Option Explicit On
Sub ChangeDocsToTxtOrRTFOrHTML()
'with export to PDF in Word 2007
Dim fs As Object
Dim oFolder As Object
Dim tFolder As Object
Dim oFile As Object
Dim strDocName As String
Dim intPos As Integer
Dim locFolder As String
Dim fileType As String
On Error Resume Next
locFolder = InputBox("Enter the folder path to DOCs", "File Conversion", "C:\Users\your_path_here\")
Select Case Application.Version
Case Is < 12
Do
fileType = UCase(InputBox("Change DOC to TXT, RTF, HTML", "File Conversion", "TXT"))
Loop Until (fileType = "TXT" Or fileType = "RTF" Or fileType = "HTML")
Case Is >= 12
Do
fileType = UCase(InputBox("Change DOC to TXT, RTF, HTML or PDF(2007+ only)", "File Conversion", "TXT"))
Loop Until (fileType = "TXT" Or fileType = "RTF" Or fileType = "HTML" Or fileType = "PDF")
End Select
Application.ScreenUpdating = False
Set fs = CreateObject("Scripting.FileSystemObject")
Set oFolder = fs.GetFolder(locFolder)
Set tFolder = fs.CreateFolder(locFolder & "Converted")
Set tFolder = fs.GetFolder(locFolder & "Converted")
For Each oFile In oFolder.Files
Dim d As Document
Set d = Application.Documents.Open(oFile.Path)
strDocName = ActiveDocument.Name
intPos = InStrRev(strDocName, ".")
strDocName = Left(strDocName, intPos - 1)
ChangeFileOpenDirectory tFolder
Select Case fileType
Case Is = "TXT"
strDocName = strDocName & ".txt"
ActiveDocument.SaveAs FileName:=strDocName, FileFormat:=wdFormatText
Case Is = "RTF"
strDocName = strDocName & ".rtf"
ActiveDocument.SaveAs FileName:=strDocName, FileFormat:=wdFormatRTF
Case Is = "HTML"
strDocName = strDocName & ".html"
ActiveDocument.SaveAs FileName:=strDocName, FileFormat:=wdFormatFilteredHTML
Case Is = "PDF"
strDocName = strDocName & ".pdf"
ActiveDocument.ExportAsFixedFormat OutputFileName:=strDocName, ExportFormat:=wdExportFormatPDF
End Select
d.Close
ChangeFileOpenDirectory oFolder
Next oFile
Application.ScreenUpdating = True
End Sub
The results are saved in a folder that is dynamically created and in the same folder that contains the documents that you just converted.
I was wondering if you could post all your code for this solution. I have been looking for something like this for a while and all my experience is on powershell. I know this i generally frowned upon but i am running out of options

"Save As" document link won't open, with error message ".. can't find .. correct location or web address"

I have an Excel Document in a Template. Users input information and Save As a new genericized number. They then hit a button that auto populates an email to one of 5 people using Vlookup and based on the cost margin.
The file is Save As'd but the e-mail recipient cannot open the file, it reads invalid location. I can close and reopen the new renamed sheet and drag it into an e-mail. I need to link to the newly saved file's name that appears in the email.
Sub Email_created_Workbook()
Dim OutApp As Object
Dim OutMail As Object
Dim Mess As Object, Recip
Recip = [Sheet1!B28].Value & "; " & [Sheet1!B27].Value
Dim strbody As String
If ActiveWorkbook.Path <> "" Then
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strbody = "<font size=""3"" face=""Calibri"">" & _
"Hello,<br><br>" & _
"There is a New PO awaiting your approval :<br><B>" & _
ActiveWorkbook.Name & "</B> is created.<br>" & _
"Click on this link to open the file : " & _
"<A HREF=""file://" & ActiveWorkbook.FullName & _
""">Link to Workbook</A>" & _
"<br><br>Regards," & _
"<br><br>Automated Approval System</font>"
On Error Resume Next
With OutMail
.To = Recip
.CC = ""
.BCC = ""
.Subject = ActiveWorkbook.Name
.HTMLBody = strbody
.Display 'or use .Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
Else
MsgBox "The ActiveWorkbook does not have a path, Save the file first."
End If
End Sub
The file name does adapt in my e-mail, from PO Template, but will not open.
I believe this will help you with your current issue (closing and reopening your file before sending). I've removed the the two lines of your code where you set the Outlook objects to Nothing. To reopen the current file you can use the OnTime function like so:
Sub Email_created_Workbook()
Dim OutApp As Object
Dim OutMail As Object
Dim Mess As Object, Recip
Recip = [Sheet1!B28].Value & "; " & [Sheet1!B27].Value
Dim strbody As String
If ActiveWorkbook.Path <> "" Then
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strbody = "<font size=""3"" face=""Calibri"">" & _
"Hello,<br><br>" & _
"There is a New PO awaiting your approval :<br><B>" & _
ActiveWorkbook.Name & "</B> is created.<br>" & _
"Click on this link to open the file : " & _
"<A HREF=""file://" & ActiveWorkbook.FullName & _
""">Link to Workbook</A>" & _
"<br><br>Regards," & _
"<br><br>Automated Approval System</font>"
On Error Resume Next
With OutMail
.To = Recip
.CC = ""
.BCC = ""
.Subject = ActiveWorkbook.Name
.HTMLBody = strbody
.Display 'or use .Send
End With
Application.OnTime Now + TimeValue("00:00:10"), "SendEmail"
ThisWorkbook.Close True 'True= yes, save changes
Else
MsgBox "The ActiveWorkbook does not have a path, Save the file first."
End If
End Sub
Sub SendEmail()
Dim OutApp As Object: Set OutApp = GetObject(, "Outlook.Application") 'Grab current instance of Outlook since we already opened the instance prior to restarting Excel
Dim oInspector As OutApp.Inspector: Set oInspector = OutApp.ActiveInspector
Dim NewMail As OutApp.MailItem: Set NewMail = oInspector.CurrentItem 'Grab currently open New/Compose Mail window
NewMail.Send 'Send Email
End Sub
Let me know if this helps resolve your issue.

How do I insert a linebreak when sending an email using VBA Access

Using the object "Outlook.Application", I send an e-mail using VBA Access. In the body, I put a string like this:
Email = "Random things" & Chr(13) _
& "More random things" & Chr(13) _
If I show the string Email in a MsgBox it is displayed correctly, but when I send it, the linebreaks are deleted.
I've tried with:
Chr(13)
vbCrLf
vbCr
But all three have the same result:
Try This:
Sub OutlookEmail()
Dim AppOutlook As Outlook.Application
Set AppOutlook = CreateObject("Outlook.application")
Dim Mail As MailItem
Set Mail = AppOutlook.CreateItem(olMailItem)
Dim Email As String
Email = "Random things" & vbNewLine _
& "More random things" & vbNewLine
'Generate Email
Mail.Subject = "Test Subject"
Mail.To = "Test#test.com"
Mail.Body = Email
Mail.Display
Set Mail = Nothing
Set AppOutlook = Nothing
End Sub
Tested it my self appears to work correctly on my PC.
The code below display the email in Outlook. To send, change .Display to .Send
Sub SendDisplayEmail(strEmailFrom As String, strEmailTo As String, strEmailCC As String, strEmailBCC As String, strSubject As String)
Dim OutApp As Object
Dim OutMail As Object
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0) ' olMailItem
Debug.Print ("From: " & strEmailFrom & ", To: " & strEmailTo & ", cc: " & strEmailCC & ", bcc: " & strEmailBCC & ", file: " & xFile)
On Error Resume Next
OutMail
With OutMail
.to = strEmailTo
.CC = strEmailCC
.BCC = strEmailBCC
.Subject = strSubject
'.Body = "Random things" _
' & vbCrLf & vbCrLf & "More random things." _
.BodyFormat = 2 ' olFormatHTML
.HTMLBody = "<html>Random things<br>More random things.</html>"
'.Body = strBody
'.Save
.Display
'.Send 'or use .Display
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
You can use the HTMLBody (with .BodyFormat = 2) for a nice formated e-mail or .Body for the plain text e-mail. Note that %0D%0A and dont work in HTMLBody because Outlook parse it.