问题
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?
回答1:
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
回答2:
Thank you so much for the help, I really appreciate it! So I made a slight variation to your code to try and get it to paste whatever is on the clipboard.
My new code is as follows. Do I need to add in any error trapping? Also, what does the option explicit exactly do?
Option Explicit
Sub Add_Hyperlinks()
Dim olNameSpace As Outlook.NameSpace
Dim wDoc As Word.Document
Dim rngSel As Word.Selection
Dim DataObj As MSForms.DataObject
Set DataObj = New MSForms.DataObject
DataObj.GetFromClipboard
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:=DataObj.GetText(1), TextToDisplay:="here"
End If
Set wDoc = Nothing
Set olNameSpace = Nothing
End Sub
来源:https://stackoverflow.com/questions/35880099/insert-hyperlink-in-outlook-body