<I thought a For Each loop in a collection would iterate through all objects
of that collection ...
It does. For example if you were changing the font color or your hyperlinks
then a basic for each loop like you wrote would be sufficient.
Sub ChangeColor()
Dim MyHLink As Hyperlink
For Each MyHLink In ActiveDocument.Hyperlinks
MyHLink.Range.Font.Color = wdColorRed
Next MyHLink
End Sub
The issue is that you are changing the number of items in the collection as
the procedure runs. This is sort of like moving the goal posts after a game
begins ;-).
Lets say you have three hyperlinks when you started running your code. Your
code deletes the first hyperlink in the first interation of the loop. Then
it deletes the second hyperlink on the next interation. Well while it was
looping Word reindexed the hyperlinks in the collection and the second
hyperlink became the first and the third became the second. A For Each loop
doesn't look back so therefore the macro ran to completiong leaving the
middle hyperlink unchanged.
If you attempt Pesach's code modified to run forward, the same sort of thing
happens but the compilier will throw an error:
Sub ConvertHyperlinksToText()
Dim i As Long
With ActiveDocument
For i = 1 To .Hyperlinks.Count
.Hyperlinks(i).Delete
Next
End With
End Sub
If you stepped through this code using the F8 key you would see that Word
deletes the first indexed hyplerlink (then reindexes the hyperlinks left in
the collection), then deletes the second indexed hyperllink (the original
third has become the second) leaving the new first untouched (the original
second became the new first) then tries to delete the third which doesn't
exists and throws the error.
Pesach's code is designed to delete the last hyperlink in the collection and
continue this until they are all gone.
In general, to delete all the objects from a collection in VBA, you need a
For loop that iterates through the collection in descending order. The
first
of the following macros converts all the hyperlinks in the active document
to
ordinary text, and the second macro completely erases all the hyperlinks. [snip]
Hope this helps,
Indeed it does, although I don't understand how your second macro is
different from mine in the end. I thought a For Each loop in a
collection would iterate through all objects of that collection. Your
goes backwards, but why does it make a difference?
Many thanks for your help!
Raph