Reason for collapse?

T

tjtjjtjt

A few days ago I posted this code to try and get a version of it that would
work on Selected text only.

Sub UnlinkHyperlinks()
Dim nHL As Long
For nHL = 1 To ActiveDocument.Hyperlinks.Count
ActiveDocument.Hyperlinks(1).Delete
Next nHL
End Sub

I had tried just changing AcitiveDocument to Selection, but I always got
Runtime error: 5941.
Several people tried to help me find out what was wrong. It turns out, the
code only fails when the selected text start at the beginning of the
hyperlink.
Does anyone have an idea as to why this would happen?

Thanks,
 
J

Jezebel

The problem is that deleting the hyperlink collapses the selection, so after
deleting the first one, the subsequent ones aren't found. (It's a feature of
VBA For ... Next loops that the limit values are not re-calculated each
time.)

The simple workaround is to delete them in reverse order --

For nHL = Selection.Hyperlinks.Count to 1 step -1
Selection.Hyperlinks(nHL).Delete
Next nHL

or

Do until Selection.Hyperlinks.Count = 0
Selection.Hyperlinks(Selection.Hyperlinks.Count).Delete
Loop
 
T

tjtjjtjt

Thanks - the workaround appeared in the original thread. What I'm curious
about is why the Selection collapses. I realize that a Selection is different
than a document, but why doesn't ActiveDocument.Hyperlinks(nHL).Delete fail
as well.
I'm sorry if I wasn't clear - I'm not looking for a workaround, I'm looking
for the reason.
 
T

Tony Jollans

Greg Maxey raised a separate post about this, titled Selection.Range
Unexpectedly Collapses (I'm sorry, I've no idea how to make links to posts
here), in the vba general group (where your original question was) and
Helmut Weber gave a brief reply, the gist of which was that when a selection
loses its beginning it has no reference point and so it just collapses. It
strikes me as being observation rather than explanation and it seems to be
one of those things which one just has to accept - the behaviour can be
clearly described and it's just the way Word does it, a feature if you will.
 
T

tjtjjtjt

That does seem to be the case. I'm usually so pleasantly surprised at what I
can get MS Office apps to do that I'm always a little chagrined when
something fails. At Greg and a couple others got me to look at it a different
way and get solution.
Thanks.
 

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