Pasting a web hyperlink into text

L

Larry

A couple of weeks ago Jay Freedman showed me this code which turns a
path of a file into a hyperlink.

If Selection.Type <> wdSelectionIP Then
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, _
Address:=Trim(Selection.Text)
End If

Now I'd like something related but more complicated.

Often in Word I'll want to apply a web address to a word or words in a
document. To do this manually, I first paste in the web address near
the target text, then press space bar to turn the web address into a
hyperlink, then I cut the target text and paste it (unformatted paste)
onto the hyperlink. The result is the text, hyperlinked to the web
address.

I'd like a simpler way to do that. I came up with a macro, but it's
clunky. I'm wondering if there's a statement hidden away in VBA that
handles this so that I don't waste my time tweaking this macro.

Thanks,
Larry

' retract from any empty space.
Selection.MoveEndWhile cset:=" ", Count:=wdBackward

ActiveDocument.Bookmarks.Add Range:=Selection.Range,
Name:="TestForHyperlink"

With Selection
.Collapse wdCollapseEnd
.MoveEndWhile cset:=" "
.Collapse wdCollapseEnd
Application.Run MacroName:="Template1.Module1.PasteAndSelect"
Application.Run MacroName:="HyperlinkFromPath"
.TypeText Text:=" "
.GoTo What:=wdGoToBookmark, Name:="TestForHyperlink"
.Cut
.Characters.First.Previous.Delete
.MoveRight wdWord, 1
.MoveRight wdWord, 1, wdExtend
End With
PasteUnformatted
 
L

Larry

This macro does what I want. I saw the possibilities in the code that
Jay had given me to be used for a different purpose, then combined that
with the Data Object stuff. This is far better than the Rube Goldberg
macro I originally pieced together. I copy a url, then select the text
in a Word document that I want to become a hyperlink to that URL, and
run the macro. Very neat.

Dim oDataObject As DataObject
Dim sAddress As String

Set oDataObject = New DataObject
' copies contents of Clipboard to Data Object
oDataObject.GetFromClipboard
sAddress = oDataObject.GetText

Set sLink = ActiveDocument.Hyperlinks.Add(Anchor:=Selection.Range, _
Address:=sAddress)

Larry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top