Wednesday, March 19, 2025

Excel VBA Macro: Save Range (as PDF) and Send as Attachment in Email

Sub save_pdf_and_attach_in_email()


Dim OutApp As Object

Dim OutMail As Object

Dim ws As Worksheet

Dim pdf_range As Range

Dim pdf_path As String


Set OutApp = CreateObject("Outlook.Application")

Set OutMail = OutApp.CreateItem(0)


Set ws = ThisWorkbook.Sheets("Sheet 1")

Set pdf_range = ws.Range("A1:C11")


pdf_path = "C:\Users\greggowaffles\Documents\Youtube Videos\Test\Stats\" & _

    "Population Data.pdf"

    

'align range in pdf

ws.PageSetup.CenterHorizontally = True

    

pdf_range.ExportAsFixedFormat Type:=xlTypePDF, _

    Filename:=pdf_path, OpenAfterPublish:=False


'create email

On Error Resume Next

    With OutMail

        .to = "team@abc.com"

        .CC = ""

        .BCC = ""

        .Subject = "Country Population Data " & Format(Date, "mm-dd-yyyy")

        .Display

        .HTMLBody = "<BODY style = 'font-size:12pt; font-family:Calibri'>" & _

            "Hi Team,<p>Please see attached pdf file.<p>Thanks,<br>Greg" & .HTMLBody

        

        .Attachments.Add pdf_path

    

    End With

    On Error GoTo 0


Set OutApp = Nothing

Set OutMail = Nothing


'Kill pdf_path


End Sub

Excel VBA Macro: Save Range (as PDF) and Send as Attachment in Email

Sub save_pdf_and_attach_in_email() Dim OutApp As Object Dim OutMail As Object Dim ws As Worksheet Dim pdf_range As Range Dim pdf_path As Str...