Last reviewed on May 1, 2014   —  19 Comments

Applies to: Applies to: Microsoft Outlook 2010 or Outlook 2007

A user in the Microsoft Answers forum wanted to know how to use a Word macro to apply formatting to selected text in Outlook 2010.

Outlook does not (and never had) a macro recorder but you can use some VBA code that was recorded in Word, in Outlook macros provided you reference the Word object model, and set the Word object and selection (as seen in the code below). You'll need to set the reference in the VB Editor's Tools, References menu. You'll also need to have macro security set to low or or sign the macro with a certificate to use it.

See How to use Outlook’s VBA Editor for help using the editor, setting security levels, and signing macros.

Reference the Word object model in Outlook's VBA Editor

I tested this macro in Outlook 2010 and Outlook 2013; it should also work in Outlook 2007.

Format Selected Text Macro

To use, open the VBA Editor (Alt+F11) and paste the code into a module. Select a block of text while composing a message and run the macro.

   Public Sub FormatSelectedText()
    Dim objItem As Object
    Dim objInsp As Outlook.Inspector
    
    ' Add reference to Word library
    ' in VBA Editor, Tools, References
    Dim objWord As Word.Application
    Dim objDoc As Word.Document
    Dim objSel As Word.Selection
    On Error Resume Next
   
'Reference the current Outlook item 
    Set objItem = Application.ActiveInspector.currentItem
    If Not objItem Is Nothing Then
        If objItem.Class = olMail Then
            Set objInsp = objItem.GetInspector
            If objInsp.EditorType = olEditorWord Then
                Set objDoc = objInsp.WordEditor
                Set objWord = objDoc.Application
                Set objSel = objWord.Selection


' replace the With block with your code
       With objSel
       ' Formatting code goes here
            .Font.Color = wdColorBlue
            .Font.Size = 18
            .Font.Bold = True
            .Font.Italic = True
            .Font.Name = "Arial"
       End With

            End If
        End If
    End If
    
    Set objItem = Nothing
    Set objWord = Nothing
    Set objSel = Nothing
    Set objInsp = Nothing
End Sub

Find and Format Text Code Sample

This example creates appointments for the selected contact(s), adds their name and address to the appointment body then changes the font used for their name and address to 14 point bold. This method can be used with any word or phrase stored in a variable.

Format specific test in an Outlook item

The original macro this code sample came from collects data from all selected contacts and creates a string to use in a single appointment but I simplified it for this example. The original macro is at Outlook 2007 Calendar.


Sub CreateAppointmentSelectedContact()

 Dim ObjItem As Object
 Dim strFullName As String
 Dim strPhone As String
 Dim strAddress As String
 Dim strDynamicDL2 As String
 Dim strDynamicDL3 As String
 Dim StartDateTime
 Dim itmAppt

 Set oContact = ObjItem
 Set objApp = CreateObject("Outlook.Application")
 Set objNS = objApp.GetNamespace("MAPI")
 Set objSelection = objApp.ActiveExplorer.Selection

 For Each ObjItem In objSelection
 If ObjItem.Class = olContact Then

 strFullName = ObjItem.FullName
 strPhone = ObjItem.HomeTelephoneNumber
 strAddress = ObjItem.HomeAddressStreet & ", " & ObjItem.HomeAddressCity & ", " & ObjItem.HomeAddressState & " " & ObjItem.HomeAddressPostalCode

 strDynamicDL2 = ("Name: ") & strFullName
 strDynamicDL3 = ("Address: ") & strAddress
 
 Set MyFolder = Session.GetDefaultFolder(9)
 Set itmAppt = MyFolder.Items.Add("IPM.Appointment")

 itmAppt.Subject = strFullName & (" -- ") & strPhone

        With itmAppt
            .Body = strDynamicDL2 & vbCrLf & strDynamicDL3
        End With

 StartDateTime = Date + 3.5
 itmAppt.Start = StartDateTime
End If
 Next

itmAppt.Display

Dim objInsp As Outlook.Inspector
Dim objWord As Word.Application
Dim objDoc As Word.Document
Dim objSel As Word.Selection


Set objInsp = itmAppt.GetInspector
Set objDoc = objInsp.WordEditor
Set objWord = objDoc.Application
Set objSel = objWord.Selection

 
 objSel.Find.ClearFormatting
 objSel.Find.Replacement.ClearFormatting
 
    With objSel.Find.Replacement.Font
       .Size = 14
       .Bold = True
       .Underline = wdUnderlineSingle
       .Color = wdColorBlack
    End With
    
    With objSel.Find
       .Text = strFullName
       .Replacement.Text = strFullName
       .Forward = True
       .Wrap = wdFindContinue
       .Format = True
       .MatchCase = False
       .MatchWholeWord = False
       .MatchWildcards = False
       .MatchSoundsLike = False
       .MatchAllWordForms = False
    End With
 objSel.Find.Execute Replace:=wdReplaceAll
 
     With objSel.Find
       .Text = strAddress
       .Replacement.Text = strAddress
       .Forward = True
       .Wrap = wdFindContinue
       .Format = True
       .MatchCase = False
       .MatchWholeWord = False
       .MatchWildcards = False
       .MatchSoundsLike = False
       .MatchAllWordForms = False
    End With
 objSel.Find.Execute Replace:=wdReplaceAll
 
Set objInsp = Nothing
Set objDoc = Nothing
Set objSel = Nothing
Set objMsg = Nothing


Set objMsg = Nothing
 Set ObjItem = Nothing
 Set objFolder = Nothing
 Set objNS = Nothing
 Set objApp = Nothing
 

 End Sub



Comments

  1. Eric Campbell says

    I tried this and got a user defined type not defined for the line
    Dim objWord As Word.Application.

    What I really want to do is have an outlook macro that does a find and replace of soome text. It was trivial to record the macro in word, but I couldn't do that in Outlook, so I am looking for a way of creating it in outlook withouot having to learn the entire internal structure of the product.

  2. True Disbeliever says

    Kewl, Diane!

    I wonder if something like the following code can be adapted to overwrite an Outlook email's styles with styles from NormalEmail.dotm.

    Here's a one-style example that I captured from Word:
    Application.OrganizerCopy Source:= _
    "C:\Users\whitney\AppData\Roaming\Microsoft\Templates\NormalEmail.dotm", _
    Destination:="Document1", Name:="Acronym", Object:=wdOrganizerObjectStyles

    Best regards,

  3. Amil says

    Thank you!!

    Also note that you can do things like ".Font.Size = .Font.Size - 1".
    My only issue is that undoing my Macro takes multiple undo steps. For example, after using your Macro, I need to press ctrl-Z 5 times to undo each of the text modifications. Any ideas?

  4. Diane Poremsky says

    I don't think you can avoid the undo issue - you are making 5 changes, so 5 undos. Remove formatting you don't want to use and only select the text you want formatted.

    With objSel
    ' Formatting code goes here
    .Font.Color = wdColorBlue
    .Font.Size = 18
    .Font.Bold = True
    .Font.Italic = True
    .Font.Name = "Arial"
    End With

  5. Cary Belas says

    Hi, if i insert a hyperlink into the email and only want this hyperlink in a large font size. how can do it ? thanks

    • Diane Poremsky says

      Manually? Select the hyperlink and format it. Depending on your stationery, you may need to change the font size after its hyperlinked. If you want all hyperlinks larger, you can change the hyperlink style.

  6. Colin says

    I've (1) copied the Format Selected Text Macro from this site, and copied two MS Word 2010 macros (that wrap the selected text in single or double quotes) into a standard module in my Outlook 2010 VBE, (2) enabled reference to the MS Word 2010 Object Library, and (3) changed Outlook macro security to notifications, but still can't get the macros to fire in Outlook!!

    Can someone (anyone??) please advise me as to what is wrong??
    Many thanks in advance.

    • Diane Poremsky says

      Remove (or comment out) all error handlers. Do you get any errors? Add msgbox "start macro" at the beginning of the macro (and some within it). Does the message box come up?

  7. Colin says

    Hi Diane
    The macros do not (yet) include error handlers. Below is the code for wrapping the selected text within single quotes. It starts, but returns a "Run time error (429) - ActiveX Component can't create object" at line 3 (lngCc = Selection.Characters.Count)

    Sub WrapStringWithSingleQuotes()

    Dim lngCc As Long
    Dim lngCw As Long

    lngCc = Selection.Characters.Count
    lngCw = Selection.Words.Count

    Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
    Selection.MoveRight Unit:=wdCharacter, Count:=1
    Selection.TypeText Text:="'"

    Select Case lngCw
    Case 1
    Selection.MoveLeft Unit:=wdCharacter, Count:=lngCc
    Case Else
    Selection.MoveLeft Unit:=wdWord, Count:=lngCw
    End Select
    Selection.TypeText Text:="'"

    End Sub

    I have no experience with Word or Outlook VBA (but am proficient with Excel VBA), so this code is from a recording, but with subsequent modifications. As a result, I appreciate that it is probably inefficient and/or uses inappropriate objects, properties & methods.
    Any re-write would be much appreciated. (As mentioned in my original post, I hoped to use the same macro to reformat text in both Word and Outlook.)

    Thanks
    Colin

    • Diane Poremsky says

      you can't just use a recorded word macro in outlook, you need to set the document and selection object so outlook knows to use it. Basically, you need to pop your code in the macro, in place of the
      With objSel
      End With

      with the dim's at the top, something like this should replace the with...end with.
      lngCc = objSel.Characters.Count
      lngCw = objSel.Words.Count

      With objSel

      .MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
      .MoveRight Unit:=wdCharacter, Count:=1
      .TypeText Text:="'"

      Select Case lngCw
      Case 1
      objSel.MoveLeft Unit:=wdCharacter, Count:=lngCc
      Case Else
      objSel.MoveLeft Unit:=wdWord, Count:=lngCw
      End Select
      objSel.TypeText Text:="'"
      End Select

      End With

  8. Colin says

    Hi again Diane
    The introductory paragraph to this article implies that Word macros can be used in Outlook?
    "..... but you can use some VBA code that was recorded in Word, in Outlook macros provided you reference the Word object model. You'll need to set the reference in the VB Editor's Tools, References menu. You'll also need to have macro security set to low or or sign the macro with a certificate to use it."

    I made the changes you suggested, and tried to run this code, but to no avail. What type of object is "objsel"?

    Sub WrapSingle()
    Dim lngCc As Long
    Dim lngCw As Long

    Dim objSel As Selection '<< Is this the correct declaration

    lngCc = objSel.Characters.Count '<< Problem here = object variable not set
    lngCw = objSel.Words.Count

    With objSel
    .MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
    .MoveRight Unit:=wdCharacter, Count:=1
    .TypeText Text:="'"

    Select Case lngCw
    Case 1
    objSel.MoveLeft Unit:=wdCharacter, Count:=lngCc
    Case Else
    objSel.MoveLeft Unit:=wdWord, Count:=lngCw
    End Select

    objSel.TypeText Text:="'"

    End With
    End Sub

    Thanks again

    • Diane Poremsky says

      objsel is how we refer to the selection object. You need to dim and set the word objects, just like in the macro on this page
      Dim objWord As Word.Application
      Dim objDoc As Word.Document
      Dim objSel As Word.Selection

      Set objDoc = objInsp.WordEditor
      Set objWord = objDoc.Application
      Set objSel = objWord.Selection

      This should work:
      Public Sub WrapSingle()
      Dim objItem As Object
      Dim objInsp As Outlook.Inspector

      ' Add reference to Word library
      ' in VBA Editor, Tools, References
      Dim objWord As Word.Application
      Dim objDoc As Word.Document
      Dim objSel As Word.Selection
      On Error Resume Next
      Dim lngCc As Long
      Dim lngCw As Long

      'Reference the current Outlook item
      Set objItem = Application.ActiveInspector.CurrentItem
      If Not objItem Is Nothing Then
      If objItem.Class = olMail Then
      Set objInsp = objItem.GetInspector
      If objInsp.EditorType = olEditorWord Then
      Set objDoc = objInsp.WordEditor
      Set objWord = objDoc.Application
      Set objSel = objWord.Selection

      lngCc = objSel.Characters.Count
      lngCw = objSel.Words.Count

      With objSel

      .MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
      .MoveRight Unit:=wdCharacter, Count:=1
      .TypeText Text:="'"

      Select Case lngCw
      Case 1
      objSel.MoveLeft Unit:=wdCharacter, Count:=lngCc
      Case Else
      objSel.MoveLeft Unit:=wdWord, Count:=lngCw
      End Select
      objSel.TypeText Text:="'"

      End With

      End If
      End If
      End If

      Set objItem = Nothing
      Set objWord = Nothing
      Set objSel = Nothing
      Set objInsp = Nothing
      End Sub

  9. Colin says

    Thanks Diane - your macro is at least now letting me access the select text, but not inserting the quote characters in the correct places, and/or is replacing/overwriting the selected text with quote characters. However, I think I can work that out with a little experimentation.

    Thanks again

  10. Steven Bayne says

    Thanks Diane, your format text macro and instructions are a life-saver.
    The one thing that I can't figure out is the code for changing the email page background. When I recorded the macro in Word the code to change the page background appears to be ActiveDocument.Background.Fill.ForeColor.RGB = RGB(182, 204, 240), but when I put this in the formatting section of the macro, the macro runs, but does not change the email background color.

    Do you have any advice?

  11. Gene Wedge says

    Great stuff! Thanks for making those connections clear. More of a pain than I thought it should be, but hey - whatever works.

  12. Scott Tsukamaki says

    Is there a way to do this without selecting the text? Something like upon open then it automatically formats it?

    • Diane Poremsky says

      do you want all of the text formatted the same? If so, yes, it can be done. For a new message, you'd just need to change the default font for that message. If you want to format just a portion, its more difficult to do.

Leave a Reply

Please post long or more complicated questions at OutlookForums by Slipstick.com.

If the Post Comment button disappears, press your Tab key.