0
votes

In MS Word, you can create hyperlinks to a "Place in this document" so that a link takes you someplace else in the same Word file. However, if you change headers or move things around these links will sometimes break. I want to write some VBA to check for broken links.

With VBA, you can list each hyperlink subaddress using the code below:

Sub CheckLinks()
    Set doc = ActiveDocument
    Dim i
    For i = 1 To doc.Hyperlinks.Count
        Debug.Print doc.Hyperlinks(i).SubAddress
    Next
End Sub

The output from the code above also matches what is shown in the field codes for the hyperlink.

However, I'm not really clear on how to verify if the SubAddress is correct. For example, an excerpt from the program output shows this:

_Find_a_Staff_1
_Edit_Organization_Settings_2
_Set_the_Staff
_Find_a_Staff_1

But there's no obvious way to tell what the "correct" suffix should be for a given heading. Any thoughts on how to check if these are valid?

Is there a way to get the list of all valid subaddresses for the headings in the document?

1
Ah, it appears that I had to set the Bookmarks.ShowHidden to true so that the hidden, automatically-created bookmarks can be searched.Taraz

1 Answers

0
votes

The code below will list the hyperlinks where the corresponding bookmark does not exist in the document. (Note that it only detects missing links, not links that go to the wrong place.)

Sub CheckLinks()
    Dim doc As Document
    Set doc = ActiveDocument
    Dim i, j
    Dim found As Boolean

    For i = 1 To doc.Hyperlinks.Count
       found = False
       For j = 1 To doc.Bookmarks.Count
         If doc.Range.Bookmarks(j).Name = doc.Hyperlinks(i).SubAddress Then
            found = True
         End If
       Next
       If found = False Then
          Debug.Print doc.Hyperlinks(i).SubAddress
       End If
    Next
End Sub