1

I am using Outlook for Office 365 (desktop).

I am trying to copy selected text from the email subject or body, and put it into a predefined web address and open it in the default browser.

Steps:

  1. Open or select a received message
  2. Select a word from the subject or body
  3. Run the macro
  4. The default browser should open the link: https://www.dictionary.com/browse/*selected word*

The code below only opens the link when the selected word is in the body of the email.

Sub OPEN_DICT()

Dim msg As Outlook.MailItem
Dim insp As Outlook.Inspector
Dim vURL1
Dim vURL2
Dim fullVID
Dim fullVURL

If Application.ActiveInspector Is Nothing Then
    If Application.ActiveExplorer.Selection.Count = 1 Then
        If Application.ActiveExplorer.Selection.Item(1).Class = olMail Then
            Set msg = Application.ActiveExplorer.Selection.Item(1)
        End If
    Else
        'to many items selected
        MsgBox "Please select one item"
    End If
Else
    Set insp = Application.ActiveInspector
    If insp.CurrentItem.Class = olMail Then
        Set msg = insp.CurrentItem
    End If
End If

If msg Is Nothing Then
    MsgBox "could not determine an item. Try again!"
Else
    If msg.GetInspector.EditorType = olEditorWord Then
        Set hed = msg.GetInspector.WordEditor
        Set appWord = hed.Application
        Set Rng = appWord.Selection
        With Rng
            .Copy
        End With

    End If
End If

If IsNumeric(Rng) Then
    fullVID = Rng
    vURL1 = "https://www.dictionary.com/browse/"
    vURL2 = fullVID
    fullVURL = vURL1 & vURL2

Else
    fullVID = Rng
    vURL1 = "https://www.dictionary.com/browse/"
    vURL2 = fullVID
    fullVURL = vURL1 & vURL2

End If

Dim build
Set build = CreateObject("Shell.Application")
build.ShellExecute "Chrome.exe", fullVURL, "", "", 1

ExitNewItem:
    Exit Sub

Set appWord = Nothing
Set insp = Nothing
Set Rng = Nothing
Set hed = Nothing
Set msg = Nothing

End Sub

How can the selected text from the Subject of the email also be opened in the link?
Also, instead of opening the link in Chrome, it should open in the default browser.

Community
  • 1
  • 1
Tarun
  • 11
  • 2

1 Answers1

0

Outlook Object Model does not expose anything that would let you access selected (or any other) text from any of its controls except for the message body editor (which is exposed as Word.Document object).

Your best bet would be finding the Subject editor using low-level Windows API (FindWindow etc.) or Automation or Accessibility API to do that. See, for example, How to get selected text of currently focused window? or How to get selected text of any application into a windows form application

Dmitry Streblechenko
  • 62,942
  • 4
  • 53
  • 78