0
votes

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.

1
Use the macro recorder to record yourself while adding the link through the right-click menu and then look at the generated code. - CherryDT
For the clipboard part, you can use DataObject and GetFromClipboard and GetText to read the contents of the clipboard, and use that instead of the status link you pasted while recording the macro. - CherryDT
Thank you. It took some work to get the DataObject and link working, - Scott Nowell

1 Answers

1
votes

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