Remove hyperlink Address

William
StarLounger
Posts: 79
Joined: 08 Feb 2010, 21:48
Location: Wellington, New Zealand

Remove hyperlink Address

Post by William »

I'm trying to devise some Word (2003 SP3) VBA code that will remove the file name (the hyperlink Address) from hyperlinks that're in the file in question. Attached is a document with such a link (don't ask how things like this come about - there are authors here who do weird things). I figured that the following code would work, but it just doesn't.

Code: Select all

Public Sub RemoveFileName()

  Dim hypEachHyperlink As Hyperlink

  With ActiveDocument
    .Fields.Update
    For Each hypEachHyperlink In .Hyperlinks
      If hypEachHyperlink.Address = .Name Then
        hypEachHyperlink.Address = vbNullString
      End If
    Next hypEachHyperlink
  End With

End Sub
Using the attached document, it seems that the hyperlink Address ("tester.doc") and the file name ("tester.doc") are the same, and stepping through the code seems to activate the "hypEachHyperlink.Address = vbNullString" part, yet nothing happens. Replacing vbNullString with "" doesn't work either.

Can anyone suggest how I could make this work? I suppose I could remove the existing hyperlink and add a new one without an Address, but I was hoping to do something simpler.
You do not have the required permissions to view the files attached to this post.

User avatar
HansV
Administrator
Posts: 78549
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Remove hyperlink Address

Post by HansV »

Try this version - test on a copy of the document:

Code: Select all

Sub RemoveFileName()
    Selection.HomeKey Unit:=wdStory
    ActiveWindow.View.ShowFieldCodes = True
    With Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = "(HYPERLINK)( " & Chr(34) & ActiveDocument.Name & Chr(34) & " )(\\l)"
        .Replacement.Text = "\1 \3"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
        .Execute Replace:=wdReplaceAll
    End With
    ActiveDocument.Fields.Update
    ActiveWindow.View.ShowFieldCodes = False
End Sub
Best wishes,
Hans

William
StarLounger
Posts: 79
Joined: 08 Feb 2010, 21:48
Location: Wellington, New Zealand

Re: Remove hyperlink Address

Post by William »

Thanks for that. Using Find and Replace was my next option, but now that you've provided the code I don't have to write it myself. :cheers:

I guess this just reinforces my longstanding belief that if manipulating Word hyperlinks using VBA, it's more reliable to treat them as fields (as hyperlinks they've always seemed to be somewhat flaky).