Reputation: 141
I have built some VBA script to convert my Excel quotation document into a PDF and the subsequently email this off to a given email address.
Currently the script is running and is able to produce the PDF document and save it down into the file location i have provided but the second part of this which is to create an email and prepare it to send wont appear to work.
I am needing this so that i can quote the customers but also store a copy of the quote in the file. I could just attach the given PDF from the file but as it will be used not only by myself i would like to remove this step.
I have tried the below code and the PDF generation works fine both in this code and in isolation. The error that comes up is a Run-time 1004 which sites this portion of the code as holding the error:
Worksheets("Email").Range("A1:g70").ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"S:\PDF Quotes\" & Format(Now, "DDMMYY-") & Worksheets("Email").Range("c12") & ".pdf", OpenAfterPublish:=True
This is despite this part working in isolation and still generating the PDF. Please see my full code below:
Sub SetEmailToPDF()
ChDir "S:\PDF Quotes"
Worksheets("Email").Range("A1:g70").ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"S:\PDF Quotes\" & Format(Now, "DDMMYY-") & Worksheets("Email").Range("c12") & ".pdf", OpenAfterPublish:=True
Dim OutLookApp As Object
Dim OutLookMailItem As Object
Dim myAttachments As Object
Set OutLookApp = CreateObject("Outlook.application")
Set OutLookMailItem = OutLookApp.CreateItem(0)
Set myAttachements = OutLookMailItem.Attachments
With OutLookMailItem
.To = "[email protected]"
.Subject = "Test Quote"
.Body = "this is a test email"
myAttachments.Add "S:\PDF Quotes\" & Format(Now, "DDMMYY-") & Worksheets("Email").Range("c12") & ".pdf"
'.send
.Display
End With
Set OutLookMailItem = Nothing
Set OutLookApp = Nothing
End Sub
As explain what i expect to see happen is the following:
1. PDF named 1`20419-companyname.pdf` is created and saved into file `S:\PDF Quotes\`
2. `120419-companyname.pdf` to be picked up and attached to an email in Outlook ready to send to `[email protected]`
Upvotes: 0
Views: 2177
Reputation: 116
I tried testing your above code and ran into issues with the code here:
myAttachments.Add "S:\PDF Quotes\" & Format(Now, "DDMMYY-") & Worksheets("Email").Range("c12") & ".pdf"
I'm thinking it's because myAttachments = OutLookMailItem.Attachments, and "OutLookMailItem" is already considered since you're using this within your With statement.
So if you change "myAttachments.Add" to ".Attachments.Add" in the code above, it should work. EDIT: how it should look below:
.Attachments.Add "S:\PDF Quotes\" & Format(Now, "DDMMYY-") & Worksheets("Email").Range("c12") & ".pdf"
Upvotes: 2