vbaoutlookms-wordhyperlinkoutlook-2010

Insert Hyperlink in Outlook body


So I am trying to create a code to expedite inserting a hyperlink in Outlook.

I am trying to have it so that if I have already copied a path, I can just go in and type Ctrl W and it will insert the hyperlink for the word here. My attempt at the code is:

Sub InsertHyperlink()
'
'
'
On Error Resume Next
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:= _
    "U:\plot.log", _
    SubAddress:="", ScreenTip:="", TextToDisplay:="here"
End Sub

I am having issues on how to update my code so that will work in Outlook (I programmed it in Word) and so that the "U:\plot.log" would actually be the copied path (not the copied path when I recorded the macro).

Does anyone have any suggestions?


Solution

  • Set your references to Word object Library

    Tools > References > add Word object Library

    Option Explicit
    Sub Add_Hyperlinks()
        Dim olNameSpace As Outlook.NameSpace
        Dim wDoc As Word.Document
        Dim rngSel As Word.Selection
    
        If Application.ActiveInspector.EditorType = olEditorWord Then
            Set wDoc = Application.ActiveInspector.WordEditor ' use WordEditor
            Set olNameSpace = Application.Session
            Set rngSel = wDoc.Windows(1).Selection ' Current selection
    
            wDoc.Hyperlinks.Add rngSel.Range, _
            Address:="U:\plot.log", TextToDisplay:="Here is the link"
        End If
    
        Set wDoc = Nothing
        Set olNameSpace = Nothing
    
    End Sub