Optimaximal
Optimaximal

Reputation: 555

Programmatically Add Hyperlink to String

I'm trying to automate Email Signature creation in VB.NET using Word Interop.

Everything works fine apart from attempting to programmatically add hyperlinks, such as (for example) an email address - it's all well and good writing the email in and expecting the other ends mail client/browser to convert it but I'd like to specify links myself (for things like social links, our privacy policy etc.)

Here are relevant segments of the code I am using:

Imports Word = Microsoft.Office.Interop.Word

Dim objWord As Word.Application = CreateObject("Word.Application")

objWord.Visible = False

Dim objDoc = objWord.Documents.Add()
Dim objSelection = objWord.Selection
Dim objEmailOptions = objWord.EmailOptions
Dim objSignatureObject = objEmailOptions.EmailSignature
Dim objSignatureEntries = objSignatureObject.EmailSignatureEntries

Try
    If Len(strEmail) > 0 Then
        objSelection.TypeText(strEmail)
    End If

Catch ex As Exception
    Debug.Print(ex.Message)
End Try

Using the example here, I believe I should be using the following in place of objSelection.TypeText(strEmail) is...

If Len(strEmail) > 0 Then
    Dim objEmailRange = objSelection.Range.Start()
    objSelection.Hyperlinks.Add(objEmailRange, strEmail, , , strEmail)    
End If

...however this throws a COM Exception.

A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in Signature_v2.exe
Command failed

Am I defining the range start correctly (based on this)? What am I doing wrong?

Upvotes: 0

Views: 1554

Answers (1)

Robert Harvey
Robert Harvey

Reputation: 180908

The hyperlink isn't the actual text; it's just a decoration on text that already exists. You have to hand a range, selection, or document to the first parameter ("Anchor") of Hyperlinks.Add().

Example:

ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:="http:\\www.microsoft.com"

Upvotes: 1

Related Questions