PDA

View Full Version : [SOLVED:] Convert selected text to a hyperlink.



bleepit
08-10-2018, 08:52 AM
A coworker wanted me to show her the other day how to quickly add a link to the FedEx website for tracking numbers she has to send through e-mail. I showed her how using the Ctrl+K method but got the idea afterward that a macro would be far better and much faster.

The idea is just for her to be able to copy and paste a tracking number into an e-mail. Highlight the tracking number, run the macro, and it would convert the tracking number into a hyperlink to the FedEx tracking website to track the highlighted tracking number.

For example:
Tracking number: 0123456789
Would become:
https://www.fedex.com/apps/fedextrack/?tracknumbers=0123456789

If I could get it to become: 0123456789 (https://www.fedex.com/apps/fedextrack/?tracknumbers=0123456789) This would be even better.


I’m still pretty new to VBA coding, but this is what I have and I can’t get it to work. I’m sure I’m missing something stupid and obvious. I was wondering if someone could take a look for me and spot what I’m doing wrong.
We are using Office 2010


Sub SelectLink()

Selection.InsertBefore Text:="https://www.fedex.com/apps/fedextrack/?tracknumbers="
Selection.InsertAfter Text:=" "
Selection.Collapse wdCollapseEnd

End Sub

Thanks so much in advance

gmayor
08-10-2018, 08:51 PM
What is not so obvious is that the coding you require is not as simple as you imagine. To insert a link from a value on the clipboard use the following.
As it detects the current window, you will need to add a button to the message ribbon or to the QAT to run the macro. It will insert the link at the cursor.
Note that the code assumes the clipboard content contains only numerals.


Option Explicit

Sub PasteLink()
Dim oRng As Object
Dim oLink As Object
Dim strLinkText As String
Const strList As String = "0123456789"
Const strLink As String = "https://www.fedex.com/apps/fedextrack/?tracknumbers="
On Error GoTo ErrHandler
If TypeName(ActiveWindow) = "Inspector" Then
If ActiveInspector.IsWordMail And ActiveInspector.EditorType = olEditorWord Then
Set oRng = ActiveInspector.WordEditor.Application.Selection.Range
oRng.PasteSpecial DataType:=2
oRng.movestartwhile strList, -1073741823
strLinkText = Trim(oRng.Text)
Set oLink = oRng.Hyperlinks.Add(Anchor:=oRng, _
Address:=strLink & strLinkText, _
SubAddress:="", _
ScreenTip:="", _
TextToDisplay:=strLinkText)
Set oRng = oLink.Range
oRng.collapse 0
oRng.Select
End If
End If
lbl_Exit:
Exit Sub
ErrHandler:
Beep
Err.Clear
GoTo lbl_Exit
End Sub

bleepit
08-13-2018, 06:19 AM
Worked perfectly!

Thank you so much!