Deleting every hyperlink in a document

F

Fool

I need to delete all the hyperlinks in a document. The following code
deletes *every other* hyperlink.

For Each oHyp In ActiveDocument.Hyperlinks
oHyp.Range.Hyperlinks(1).Delete
Next


I made the code functional by adding a While Loop (below), but it's
rather inefficent. It doesn't seem like the While loop should be
necessary, but it is. Why?


While ActiveDocument.Hyperlinks.Count > 0
For Each oHyp In ActiveDocument.Hyperlinks
oHyp.Range.Hyperlinks(1).Delete
Next
Wend


Thanks.
 
D

Dave

i believe its something like this... when you delete the first oHyp the next
one is moved up the list of hyperlinks and actually fills the place in the
list that the one you just deleted was in... then when the next occurs it
moves on to the next one and actually leaves the one that was the next one
before you deleted the first one behind. it then deletes the next next one
which slides the next next next one up one and so on ad nauseum. basically
the 'for each' is only good as long as the content of the list you are
itterating through doesn't change while you are doing it.

just do a while and keep deleting the first hyperlink until they are all
gone... its something like this anyway.
While ActiveDocument.Hyperlinks.Count > 0
ActiveDocument.Hyperlinks.Range.Hyperlinks(1).Delete
Wend
is this right??? i haven't checked it, do you need the Range in there?? you
can sort it out now i think.
 
G

George Nicholson

Try:
For Each oHyp In ActiveDocument.Hyperlinks
oHyp.Delete
Next

Your original code appears to be deleting the 1st hyperlink within the range
of each hyperlink (but not necessarily the "container" hyperlink itself)?
Not really sure since I'm not quite sure about the Range property of a
Hyperlink but I think that's where your problem is.

Your While loop worked because it kept repeating the For...Each loop until
Hyperlinks.Count got to 0.
 
P

Peter

The reasons for the behavior of your code have been explained in previous posts, so just to give you a third option:

Dim i As Integer
With ActiveDocument.Hyperlinks
For i = .Count To 1 Step -1
''' do ONE of the following (comment/delete the other):
.Item(i).Delete ' deletes just the hyperlink
.Item(i).Range.Delete ' deletes the hyperlink and the text associated with it
Next i
End With

hth,

-Peter
 

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