human12345
New Member
- Joined
- Feb 10, 2023
- Messages
- 3
- Office Version
- 365
- Platform
- Windows
Hello,
Ultimately, I am trying to have my excel sheet saved as a PDF and then emailed. I have figured out a way to do that, however once I started tweaking it, I realized I am way out of my league.
I need to also be able to:
(1) save the file as the value in cell A40 of the current sheet,
(2) save the PDF in the same location the excel file is located (right now it is specific to C:\Folder, however the file is not always in the same location, so this needs to be variable), and
(3) rename the file with a sequential number if there is an existing file.
Help would be greatly appreciated!
Ultimately, I am trying to have my excel sheet saved as a PDF and then emailed. I have figured out a way to do that, however once I started tweaking it, I realized I am way out of my league.
I need to also be able to:
(1) save the file as the value in cell A40 of the current sheet,
(2) save the PDF in the same location the excel file is located (right now it is specific to C:\Folder, however the file is not always in the same location, so this needs to be variable), and
(3) rename the file with a sequential number if there is an existing file.
Help would be greatly appreciated!
VBA Code:
Sub EmailAsPDF()
Dim strFileName As String
Dim strFileExists As String
strFileName = "C:\Folder\" & Range("A40").Value & ".pdf"
strFileExists = Dir(strFileName)
If strFileExists = "" Then
'The selected file doesn't exist
ChDir "C:\Folder"
'Print to PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=Range("A40").Value, OpenAfterPublish:=True
'Declare Variables
Dim EmailApp As Object
Dim EmailItem As Object
Dim myAttachments As Object
'Set Variables
Set EmailApp = CreateObject("Outlook.application")
Set EmailItem = EmailApp.CreateItem(0)
Set myAttachments = EmailItem.Attachments
'Specify Email Items and Add Attachment
With EmailItem
.To = ""
.bcc = ""
.Subject = Range("A40").Value
.Body = "Please see attached."
.Attachments.Add "C:\Folder\" & Range("A40").Value & ".pdf"
'.send
.Display
End With
Set EmailItem = Nothing
Set EmailApp = Nothing
Else
'The selected file exists
ChDir "C:\Folder"
'Print to PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=Range("A40").Value & "(1)", OpenAfterPublish:=True
'Set Variables
Set EmailApp = CreateObject("Outlook.application")
Set EmailItem = EmailApp.CreateItem(0)
Set myAttachments = EmailItem.Attachments
'Specify Email Items and Add Attachment
With EmailItem
.To = ""
.bcc = ""
.Subject = Range("A40").Value & "(1)"
.Body = "Please see attached."
.Attachments.Add "C:\Folder\" & Range("A40").Value & "(1).pdf"
'.send
.Display
End With
Set EmailItem = Nothing
Set EmailApp = Nothing
End If
End Sub