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.
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.
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, "&", "&")
s = Replace(s, "<", "<")
s = Replace(s, ">", ">")
HtmlEscape = s
End FunctionHow to use it
- Open the workbook and press
Alt+F11(Mac:Opt+F11orFn+Opt+F11) to open the VBA editor. See The Developer tab and the VBA editor if you have never used it. - Choose Insert › Module. An empty code window opens on the right.
- Paste the whole code into that window. If the module already starts with
Option Explicit, do not paste that line twice. - Go back to Excel, press
Alt+F8(Mac:Opt+F8, or Tools › Macro › Macros), pickEmailSelectionInBodyand click Run. - Change the address and subject in the code, select the range (headings in the first row), then run it.
- 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:
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 FunctionThen 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
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.
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.