PDA

View Full Version : [SOLVED:] VBA Hyperlink.Delete does not work properly



ievakr
03-16-2022, 08:39 AM
Hello,
What I want to do, is for macro to find all hyperlinks with word "servlet" in the address and delete the hyperlink:



Sub Link()


Dim H As Hyperlink
For Each H In ActiveDocument.Hyperlinks
If InStr(H.Address, "servlet") <> 0 Then
H.Delete
End If
Next H
End Sub


But H.Delete breaks the Next H function and in result only every second hyperlink is deleted and I have to run the macro again. Meanwhile H.Follow works like a charm in this code.
What can it be?

Chas Kenyon
03-16-2022, 09:26 AM
Step backwards rather than forward when going through a collection where you are deleting members of the collection. This is a common problem.


Sub Link()
' Charles Kenyon 16 March 2022
' http://www.vbaexpress.com/forum/newreply.php?do=postreply&t=69739
' macro to find all hyperlinks with word "servlet" in the address and delete the hyperlink
'
Const strFindWord = "servlet" ' text to find in hyperlink's address
Dim H As Hyperlink, iH As Long, iCount As Long
Let iH = ActiveDocument.Hyperlinks.Count
For iCount = iH To 1 Step -1
Set H = ActiveDocument.Hyperlinks(iCount)
If InStr(H.Address, strFindWord) <> 0 Then
H.Delete
End If
Next iCount
Set H = Nothing
End Sub

Chas Kenyon
03-16-2022, 10:26 AM
Cross-posted at https://www.msofficeforums.com/word-vba/48681-hyperlink-delete-does-not-work-properly.html.

For cross-posting etiquette, please read: A Message to Forum Cross-Posters (https://www.excelguru.ca/content.php?184)

ievakr
03-17-2022, 12:50 AM
Thank you, it worked!