Scott Nowell
Scott Nowell

Reputation: 56

word use vba to create a hyperlink from clipboard

I have copied a hyperlink into the clipboard.
In a Word docx I have selected some text and want to convert the text to be a hyperlink to the data on the clipboard.

I can manually do this by right-clicking the selected text, selecting Link-> and either clicking the item from recent links, or selecting Link-> then Insert Link and pasting the clipboard into the address.

I would like to do this in a macro that I can assign to a key as a shortcut. E.g., copy the link to the clipboard in another program then in Word press a single key to have the selected text become a hyperlink to the address on the clipboard.

Upvotes: 0

Views: 951

Answers (1)

Scott Nowell
Scott Nowell

Reputation: 56

Thanks CherryDT, Here is the final VBA:

Sub AddHyperLink()
'
' AddHyperLink Macro
'
' 20-Apr-20
' Converts the selected test into a hyperlink
' The URL must be in the clipboard
'
'

    Dim MyData As DataObject
    Dim strAddr As String
    Dim strTitle As String

    Set MyData = New DataObject
    MyData.GetFromClipboard
    strAddr = MyData.GetText

    Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
    Selection.Copy
    MyData.GetFromClipboard

    ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:=strAddr _
        , SubAddress:="", ScreenTip:="", TextToDisplay:=Selection.Range
End Sub

Upvotes: 1

Related Questions