Home > Back-end >  Simple Outlook macro to convert selected text to 'code'
Simple Outlook macro to convert selected text to 'code'

Time:11-01

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've copied some code I found in another answer and tweaked it, but no dice, and I fear I'm missing something obvious.

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'm not a VBA guy, so it's likely something obvious :) I'm not even sure if it's a problem with the code or with the general macro support.

FWIW, in the past I wrote a separate VBA script to throw a warning message when I send an email to multiple people with different email domains (to avoid accidental data cross-sharing) which works fine, so I know a little bit...

To be clearer, I have added this code into a macro within the ThisOutlookSession object

enter image description here

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

CodePudding user response:

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.

  • Related