roryhewitt
roryhewitt

Reputation: 4507

Convert selected text to specified font

I'm trying to create a macro in Outlook to allow me to select text and convert that text to 'code' (Courier New, black). I'm using Outlook for Microsoft 365 which, I think, uses the Word editor.

I copied code I found in another answer and tweaked it.

Public Sub FormatSelectedText()
    Dim objItem As Object
    Dim objInsp As Outlook.Inspector
    Dim objWord As Word.Application
    Dim objDoc As Word.Document
    Dim objSel As Word.Selection
    On Error Resume Next

    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
                With objSel
                    .Font.Name = "Courier New"
                    .Font.Color = RGB(0, 0, 0)
                End With
            End If
        End If
    End If

End Sub

I have this code in ThisOutlookSession.
enter image description here

I open a new email, add some random text, select some of the text and run the macro, but the text in the email body doesn't change.

Upvotes: 0

Views: 199

Answers (1)

Eugene Astafiev
Eugene Astafiev

Reputation: 49397

The code works correctly. You just need to add a COM reference to the Word object model to be able to use the Word object model in Outlook VBA macros.

  1. In VBA editor window, click the “Tools” button in the menu bar.

    VBA COM references

  2. Then, from the drop down list, select the “References” option.

  3. The “References – Project 1” dialog box will display.

  4. In this dialog box, you can pull the scrolling bar down until you locate what you need, in your case it is “Microsoft Word 16.0 Object Library”.

  5. Mark the checkbox in front of the required entry and click “OK”.

Now you have added the Word object library reference successfully.

Upvotes: 1

Related Questions