Insert Hyperlink - won't work in Word 2007


L

Lee Kiwiflame

I had some code that use to work in previous versions of Word but since
upgrading to Word 2007, the macro won't work.

Sub Hyperlink()

Dim fd As FileDialog, displaytext As String
'Create a FileDialog object as a File Picker dialog box.
Set fd = Application.FileDialog(msoFileDialogFilePicker)
'Use a With...End With block to reference the FileDialog object.
With fd
'Set the initial path to the Agenda Attachments folder.
.InitialFileName = "M:\processes\documents\agenda attachments\"
.Title = "Select the File to which you want to create the link"
'Use the Show method to display the File Picker dialog box and
return the user's action.
'If the user presses the action button...
If .Show = -1 Then
displaytext = .SelectedItems(1)
While InStr(displaytext, "\") > 0
displaytext = Mid(displaytext, InStr(displaytext, "\") + 1)
Wend
displaytext = Left(displaytext, Len(displaytext) - 4)
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range,
Address:=.SelectedItems(1), TextToDisplay:=displaytext
' 'If the user presses Cancel...
Else
End If
End With

'Set the object variable to Nothing.
Set fd = Nothing

End Sub

I've debugged the above and it seems to be the TextToDisplay:=displaytext
part which has the issue. If I remove this, the macro works. However, I
need to just display the selected filename, not the whole file path.

Please note that this code was written for me by a MVP on here so I'm not
sure exactly what it is doing between the While and Wend statements.

Thanks
 
Ad

Advertisements

T

Tony Jollans

What do you mean by "won't work"?

What does it do, if anything, or what error message does it give?
 
L

Lee Kiwiflame

It crashes MS Word. When Word restarts, the hyperlink is inserted but it's
the full path of the link, not just the filename of the document which is
linked.
 
Ad

Advertisements

T

Tony Jollans

I see now. That shouldn't happen.

Although I'm not sure what the problem is, you can stop it happening by
changing

Dim fd As FileDialog, displaytext As String

to

Dim fd As FileDialog, displaytext
 

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