DA said:
Jonathan,
Quick question.
When I initially tried my routine it worked, yet after
reading yours and Simon's follow up, I revisited another
test case and bingo.. it missed various links in a test
doc.
Is this a known quirk in Word.. or why won't it cycle
through each link if you state for each hyperlink in
ActiveDocument.Hyperlinks ?
The reason is that a For Each loop counts upwards. So the first time you go
round the loop, it deletes the first hyperlink. The second time, it deletes
the second hyperlink - of the ones which are remaining! So your macro only
deletes every second hyperlink.
What mine does is check how many hyperlinks there are, and in the loop it
deletes the first hyperlink of those remaining in the document until there
are no more.
If it were necessary to delete only certain links (e.g. only delete links to
other documents) then it would be necessary to take another approach - to
count backwards. To delete all links whose Address property is not blank,
you would need to do this
Sub RemoveExternalHyperlinks()
Dim n as Long
With ActiveDocument.Hyperlinks
For n = .Count To 1 Step -1
If Len(.Item(n).Address) > 0 Then
.Item(n).Delete
End If
Next n
End With
End Sub
Whenever you deal with collections in the Word object model, and you have a
loop which adds or deletes items from the collection, tyou have to be very
careful with the indexing to be sure that you really are manipulating the
item you think you are. Some collections behave the way collections should
(and are documented to) and automatically readjust their indexes when an
itenm is added, some (like the Hyperlinks collection) do not. Because the
varying behaviour is not documented, I would strongly recommend that you do
not rely on it being one way or the other, or even remaining the same way
between versions of Word.