VBA macros · Email and other Office apps

VBA macro to send a range in the body of an Outlook email

Put the selected Excel range into the body of an Outlook email as a formatted table, above your normal signature. Windows and classic Outlook.

Windows only

A daily sales summary or a short status table is easier to read in the email itself than in an attachment, especially on a phone. Copying and pasting works but is easy to get wrong. This macro turns the selected range into a simple HTML table, with headings in bold and numbers right-aligned, and places it in a new Outlook email above your signature.

VBA
Option Explicit

Sub EmailSelectionInBody()
    Dim rng As Range
    Dim olApp As Object, olMail As Object

    If TypeName(Selection) <> "Range" Then Exit Sub
    Set rng = Selection.Areas(1)

    On Error Resume Next
    Set olApp = GetObject(, "Outlook.Application")
    On Error GoTo Fail
    If olApp Is Nothing Then Set olApp = CreateObject("Outlook.Application")

    Set olMail = olApp.CreateItem(0)
    With olMail
        .To = "team@example.com"
        .Subject = "Sales summary " & Format(Date, "yyyy-mm-dd")
        .Display                                ' adds the default signature
        .HTMLBody = "<p>Hello,</p><p>Here are today's figures:</p>" & _
                    RangeToHtmlTable(rng) & "<p>Best regards</p>" & .HTMLBody
    End With
    Exit Sub

Fail:
    MsgBox "Could not create the email: " & Err.Description, vbExclamation
End Sub

Private Function RangeToHtmlTable(rng As Range) As String
    Dim r As Long, c As Long
    Dim html As String, tag As String, align As String

    html = "<table style=""border-collapse:collapse;font-family:Calibri,Arial,sans-serif;font-size:11pt"">"
    For r = 1 To rng.Rows.Count
        html = html & "<tr>"
        For c = 1 To rng.Columns.Count
            If r = 1 Then tag = "th" Else tag = "td"
            If IsNumeric(rng.Cells(r, c).Value) And Not IsEmpty(rng.Cells(r, c).Value) Then
                align = "right"
            Else
                align = "left"
            End If
            html = html & "<" & tag & " style=""border:1px solid #bbbbbb;padding:4px 8px;text-align:" & _
                   align & """>" & HtmlEscape(rng.Cells(r, c).Text) & "</" & tag & ">"
        Next c
        html = html & "</tr>"
    Next r
    RangeToHtmlTable = html & "</table>"
End Function

Private Function HtmlEscape(ByVal s As String) As String
    s = Replace(s, "&", "&amp;")
    s = Replace(s, "<", "&lt;")
    s = Replace(s, ">", "&gt;")
    HtmlEscape = s
End Function
Email the selected range as a table in the message body

How to use it

  1. Open the workbook and press Alt+F11 (Mac: Opt+F11 or Fn+Opt+F11) to open the VBA editor. See The Developer tab and the VBA editor if you have never used it.
  2. Choose Insert › Module. An empty code window opens on the right.
  3. Paste the whole code into that window. If the module already starts with Option Explicit, do not paste that line twice.
  4. Go back to Excel, press Alt+F8 (Mac: Opt+F8, or Tools › Macro › Macros), pick EmailSelectionInBody and click Run.
  5. Change the address and subject in the code, select the range (headings in the first row), then run it.
  6. Save the file as an Excel Macro-Enabled Workbook (.xlsm). A normal .xlsx file throws the code away when you save it.

To have this macro ready in every workbook, keep it in your Personal Macro Workbook (PERSONAL.XLSB). If you do not have one yet, record any tiny macro with Store macro in: Personal Macro Workbook (see The macro recorder: record, read and clean up code), then paste this code into a module under VBAProject (PERSONAL.XLSB). The macro works on whichever workbook is active when you run it.

How it works

Outlook connects the same way as in VBA macro to send the active workbook by Outlook email: GetObject reuses a running Outlook and CreateObject starts one if needed. Only the first block of the selection is used (Selection.Areas(1)), because a table needs one rectangle.

RangeToHtmlTable builds the table as text. It walks through the range row by row and cell by cell. The first row becomes heading cells, which mail programs show in bold, and the rest become normal cells. Each cell gets a thin border and padding through inline styles, because many mail programs ignore style sheets. Numbers are right-aligned so columns of figures line up.

The cell content is taken from .Text, the value exactly as Excel displays it, so 1250.5 formatted as currency arrives as €1,250.50 and dates keep their format. HtmlEscape replaces the three characters that have a special meaning in HTML; otherwise a value like Tom & Jerry or <5 items could break the layout.

The order of the last lines matters: .Display opens the message, and at that moment Outlook inserts your default signature into .HTMLBody. Adding the table in front of the existing .HTMLBody keeps the signature below it. Text building with & is covered in Working with text (strings) in VBA.

Change it

To send a fixed range instead of the selection, use Set rng = ThisWorkbook.Worksheets("Summary").Range("A1:E12"). If the range grows, combine it with the last-row techniques from Find the last row and build dynamic ranges in VBA.

To copy fill colours from Excel, add the cell's colour to the style. Excel stores colours as BGR numbers, so they have to be turned around for HTML:

VBA
Private Function CssColor(ByVal excelColor As Long) As String
    ' Excel colour (BGR) to an HTML colour such as #FFC7CE
    CssColor = "#" & Right$("0" & Hex(excelColor And &HFF), 2) & _
                     Right$("0" & Hex((excelColor \ &H100) And &HFF), 2) & _
                     Right$("0" & Hex((excelColor \ &H10000) And &HFF), 2)
End Function
Convert an Excel colour to an HTML colour code

Then add "background:" & CssColor(rng.Cells(r, c).Interior.Color) & ";" inside the style text. To attach the workbook as well, add .Attachments.Add as in the workbook macro. Replace .Display with .Send only once you are happy with the result; then the signature step does not apply.

What can go wrong

Watch out. These macros drive classic Outlook for Windows through its automation interface. The new Outlook for Windows, Outlook on the web and Outlook for Mac do not support it, so CreateObject fails with error 429 (ActiveX component can't create object). If you have switched to the new Outlook, turn the New Outlook toggle off, or save the file and attach it by hand.

Cells that show #### because the column is too narrow are sent as ####, since .Text returns what is on screen. Auto-fit the columns before running. Merged cells, pictures, charts and conditional formatting are not transferred; for an exact visual copy, paste the range as a picture by hand.

Very large ranges make a heavy email and slow loop. Keep it to a summary of a few dozen rows; send larger data as an attachment instead.

Tip. Windows-only, because Outlook automation is not available in Excel for Mac. The table looks the same in Outlook, Gmail and phone mail apps because it uses simple inline styles.

Related: VBA macro to send the active workbook by Outlook email, VBA macro to export a range as PDF in Excel, Control Outlook, Word and PowerPoint from Excel VBA.

More vba macros