VBA course · Lesson 31 of 33

Control Outlook, Word and PowerPoint from Excel VBA

Send Outlook emails with tables and attachments, fill a Word template from Excel and understand early vs late binding, with notes on security and Mac limits.

Advanced 22 min read

Excel rarely works alone. The monthly sales report ends up as an email, the contract data becomes a Word letter, the chart lands on a PowerPoint slide. Because Outlook, Word and PowerPoint expose the same kind of object model as Excel, your Excel macros can drive them too: create an email, fill in a Word document, add a slide. This technique is called automation.

This lesson covers the key idea that makes it possible (binding to another application), then walks through the three most common jobs: sending emails with Outlook, filling a Word template and pasting a chart into PowerPoint. Everything here is Windows-first; the Mac section at the end explains what changes.

Early binding and late binding

To control Word from Excel, VBA needs an object that represents Word. There are two ways to get one.

Early binding

You tell the VBA project in advance which application's object library you will use: in the VBA editor choose Tools > References and tick, for example, Microsoft Outlook 16.0 Object Library. Then you can declare variables with the real types:

VBA
Option Explicit

Sub EarlyBoundHello()
    Dim olApp As Outlook.Application
    Dim mail As Outlook.MailItem

    Set olApp = New Outlook.Application
    Set mail = olApp.CreateItem(olMailItem)
    mail.To = "[email protected]"
    mail.Subject = "Test from Excel"
    mail.Body = "Hello from VBA."
    mail.Display
End Sub
Early binding: needs Tools > References > Microsoft Outlook xx.0 Object Library

Advantages: IntelliSense lists all properties as you type, named constants such as olMailItem work, the compiler catches typos, and calls are slightly faster. Disadvantage: the reference points to a specific library version. If a colleague has a different Office version, or no Outlook at all, the workbook may show "Can't find project or library" and none of its macros compile, not even the ones that have nothing to do with Outlook.

Late binding

With late binding you declare the variables As Object and create the application at run time with CreateObject. No reference is needed.

VBA
Option Explicit

Sub LateBoundHello()
    Const olMailItem As Long = 0          ' constants must be defined yourself
    Dim olApp As Object
    Dim mail As Object

    Set olApp = CreateObject("Outlook.Application")
    Set mail = olApp.CreateItem(olMailItem)
    mail.To = "[email protected]"
    mail.Subject = "Test from Excel"
    mail.Body = "Hello from VBA."
    mail.Display
End Sub
Late binding: works without any reference

The code looks almost the same, but the program is found only when the line runs, so it works with whatever version of Outlook is installed. The price: no IntelliSense, and the library's named constants are unknown, so you define the ones you need with Const (look up their values in the Object Browser, F2, while a reference is set, or in Microsoft's documentation).

Tip. A popular workflow: develop with early binding to enjoy IntelliSense, then switch to late binding before you share the file: change the types to Object, replace New with CreateObject, add Const lines for the constants, and untick the reference.
ApplicationCreateObject class nameCommon constants (value)
OutlookOutlook.ApplicationolMailItem (0), olFormatHTML (2)
WordWord.ApplicationwdFormatPDF (17), wdPasteDefault (0)
PowerPointPowerPoint.ApplicationppLayoutBlank (12), ppPasteEnhancedMetafile (2)

GetObject(, "Word.Application") attaches to a copy of Word that is already running and raises an error if there is none. Outlook allows only one running instance, so CreateObject("Outlook.Application") simply returns the open one if Outlook is already running.

Sending emails with Outlook

Display first, send later

A mail item has two ways to finish: .Display opens the message window so a person can check and press Send, and .Send sends it straight away. While you are developing, always use .Display. A loop with a bug and .Send can email the wrong numbers to 200 customers in two seconds, and there is no undo.

An email with a table and an attachment

The following macro emails a short sales summary as an HTML table and attaches the current workbook's PDF report. The table is built from the sheet below.

ABC
1RegionOrdersRevenue
2North14238450
3South9627120
4West11831980

The Summary sheet

VBA
Option Explicit

Sub EmailSalesSummary()
    Const olMailItem As Long = 0
    Dim olApp As Object
    Dim mail As Object
    Dim ws As Worksheet
    Dim html As String
    Dim r As Long
    Dim pdfPath As String

    Set ws = ThisWorkbook.Worksheets("Summary")

    ' 1. Save the summary sheet as a PDF to attach
    pdfPath = Environ$("TEMP") & "\Sales summary " & Format(Date, "yyyy-mm-dd") & ".pdf"
    ws.ExportAsFixedFormat Type:=xlTypePDF, fileName:=pdfPath

    ' 2. Build an HTML table from A1:C4
    html = "<p>Hello team,</p><p>Here are this week's figures:</p>" & _
        "<table border='1' cellpadding='4' style='border-collapse:collapse'>"
    For r = 1 To 4
        html = html & "<tr>" & _
            "<td>" & ws.Cells(r, 1).Text & "</td>" & _
            "<td align='right'>" & ws.Cells(r, 2).Text & "</td>" & _
            "<td align='right'>" & ws.Cells(r, 3).Text & "</td></tr>"
    Next r
    html = html & "</table><p>Full report attached.</p>"

    ' 3. Create and show the email
    Set olApp = CreateObject("Outlook.Application")
    Set mail = olApp.CreateItem(olMailItem)
    With mail
        .To = "[email protected]"
        .CC = ""
        .Subject = "Weekly sales summary " & Format(Date, "d mmm yyyy")
        .HTMLBody = html
        .Attachments.Add pdfPath
        .Display            ' change to .Send only when everything is tested
    End With
End Sub
Email an HTML summary table with a PDF attachment (late binding)

What each part does:

  • Environ$("TEMP") returns the Windows temporary folder, a good place for files you only need to attach.
  • .Text returns what the cell shows, including number formatting such as thousands separators, which is what you want in an email. .Value would give the raw number.
  • .HTMLBody takes HTML, so tables, bold text and links are possible. Use .Body for plain text.
  • .Attachments.Add takes a full file path. Call it once per file.

To keep the user's Outlook signature, call .Display before setting .HTMLBody, then write .HTMLBody = html & .HTMLBody: the signature is inserted when the window opens.

One email per row

Combine this with a loop (For loops: For...Next and For Each) to send personalised messages: one row per customer with an email address, a name and an amount due. Build the body text with the row's values, and display the first few to check before switching to .Send.

VBA
Option Explicit

Sub SendPaymentReminders()
    Const olMailItem As Long = 0
    Dim olApp As Object
    Dim mail As Object
    Dim ws As Worksheet
    Dim r As Long
    Dim lastRow As Long
    Dim sent As Long

    Set ws = ThisWorkbook.Worksheets("Overdue")
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    Set olApp = CreateObject("Outlook.Application")

    For r = 2 To lastRow
        ' Columns: A customer, B email, C invoice, D amount, E reminded?
        If ws.Cells(r, "B").Value <> "" And ws.Cells(r, "E").Value <> "Yes" Then
            Set mail = olApp.CreateItem(olMailItem)
            With mail
                .To = ws.Cells(r, "B").Value
                .Subject = "Reminder: invoice " & ws.Cells(r, "C").Value
                .Body = "Dear " & ws.Cells(r, "A").Value & "," & vbCrLf & vbCrLf & _
                    "Our records show that invoice " & ws.Cells(r, "C").Value & _
                    " for " & Format(ws.Cells(r, "D").Value, "#,##0.00") & _
                    " EUR is still open. Please arrange payment at your convenience." & _
                    vbCrLf & vbCrLf & "Kind regards," & vbCrLf & "Accounts team"
                .Display                       ' review each one; switch to .Send later
            End With
            ws.Cells(r, "E").Value = "Yes"     ' log it, so nobody is reminded twice
            sent = sent + 1
        End If
    Next r

    MsgBox sent & " reminder(s) prepared.", vbInformation
End Sub
Personalised payment reminders, one per overdue customer

Writing "Yes" in column E after each email makes the macro safe to run again: customers who were already reminded are skipped.

Security prompts

Older Outlook versions and some company setups show a warning such as "A program is trying to send an e-mail message on your behalf" when code calls .Send or reads addresses. This is a deliberate protection against viruses. Do not try to work around it with third-party tools; if your organisation needs unattended sending, ask IT to configure it properly. Using .Display and letting the person press Send avoids the prompt entirely.

Note. The new Outlook for Windows (the redesigned app that replaces classic Outlook) does not support VBA automation. CreateObject("Outlook.Application") needs classic Outlook to be installed. Check which version your users have.

Filling a Word template

A Word template with bookmarks is a tidy way to produce letters and contracts. In Word, place the cursor where a value should go and choose Insert > Bookmark, giving names such as CustomerName, InvoiceNo and AmountDue. Save the file as Reminder template.docx next to your workbook.

VBA
Option Explicit

Sub CreateWordLetter()
    Const wdFormatPDF As Long = 17
    Dim wdApp As Object
    Dim doc As Object
    Dim ws As Worksheet
    Dim templatePath As String
    Dim outPath As String
    Dim sep As String

    sep = Application.PathSeparator
    Set ws = ThisWorkbook.Worksheets("Overdue")
    templatePath = ThisWorkbook.Path & sep & "Reminder template.docx"
    outPath = ThisWorkbook.Path & sep & "Letter " & ws.Range("C2").Value & ".pdf"

    Set wdApp = CreateObject("Word.Application")
    wdApp.Visible = False                     ' work in the background
    On Error GoTo CleanUp

    ' Documents.Add with a template creates a new, unsaved copy of it
    Set doc = wdApp.Documents.Add(Template:=templatePath)
    FillBookmark doc, "CustomerName", ws.Range("A2").Value
    FillBookmark doc, "InvoiceNo", ws.Range("C2").Value
    FillBookmark doc, "AmountDue", Format(ws.Range("D2").Value, "#,##0.00")

    doc.SaveAs2 outPath, wdFormatPDF

CleanUp:
    If Not doc Is Nothing Then doc.Close SaveChanges:=False
    wdApp.Quit                                ' always close the hidden Word
    If Err.Number <> 0 Then MsgBox "Word error: " & Err.Description, vbExclamation
End Sub

Private Sub FillBookmark(ByVal doc As Object, ByVal bmName As String, ByVal text As String)
    If doc.Bookmarks.Exists(bmName) Then
        doc.Bookmarks(bmName).Range.Text = text
    End If
End Sub
Create a Word letter from a template and save it as PDF

Three points deserve attention. wdApp.Visible = False keeps Word hidden, which is faster, but if the macro stops halfway a hidden WINWORD.EXE stays in memory, which is why Quit sits in the clean-up section. Documents.Add(Template:=...) leaves the template file untouched. And SaveAs2 with format 17 writes a PDF directly; use 16 (wdFormatDocumentDefault) for a .docx.

PowerPoint in brief

PowerPoint works the same way. This macro copies a chart from Excel onto a new blank slide (Create and format charts with VBA shows how to build the chart).

VBA
Option Explicit

Sub ChartToPowerPoint()
    Const ppLayoutBlank As Long = 12
    Dim pptApp As Object
    Dim pres As Object
    Dim sld As Object

    Set pptApp = CreateObject("PowerPoint.Application")
    pptApp.Visible = True                    ' PowerPoint needs a visible window to paste
    Set pres = pptApp.Presentations.Add
    Set sld = pres.Slides.Add(1, ppLayoutBlank)

    ThisWorkbook.Worksheets("Dashboard").ChartObjects(1).Chart.ChartArea.Copy
    sld.Shapes.Paste

    ' Position the pasted chart (points: 72 per inch)
    With sld.Shapes(sld.Shapes.Count)
        .Left = 40
        .Top = 40
        .Width = 640
    End With
End Sub
Paste an Excel chart into a new PowerPoint slide

Copy-and-paste between applications occasionally fails if the clipboard is busy; if you meet random errors on Paste, add DoEvents before it or retry once.

On a Mac

Office for Mac runs each application in its own sandbox, and CreateObject for other Office applications is not supported in a reliable way: CreateObject("Outlook.Application") does not work, and Word or PowerPoint automation from Excel is limited and fragile. The supported route is AppleScriptTask: you write a small AppleScript file, place it in the user's ~/Library/Application Scripts/com.microsoft.Excel folder, and call one of its handlers from VBA with AppleScriptTask("MyScript.scpt", "HandlerName", parameter). That script can then create an email in Outlook for Mac or Apple Mail. Because each user must install the script file once, this is suitable for in-house tools rather than for files you hand to strangers.

Common mistakes

  • Sending with .Send while testing; use .Display until the output is right.
  • Using early binding in a shared workbook and breaking it for anyone with a different Office version.
  • Using a constant such as olMailItem with late binding and no Const: with Option Explicit it will not compile; without it, the value is silently 0 or Empty, which happens to work for olMailItem but not for others.
  • Leaving invisible Word or PowerPoint processes behind after an error; always quit in a clean-up block.
  • Putting the email body together from cell .Values and getting unformatted numbers like 38450.5 instead of 38,450.50.

Check yourself

1. What is the main advantage of late binding?

2. With late binding, how do you use a constant like olMailItem?

3. Which method should you use while testing an email macro?

4. Why does the Word example call wdApp.Quit in the clean-up section?

5. What is the supported way to automate Outlook from Excel VBA on a Mac?