Consulting

Results 1 to 4 of 4

Thread: VBA Hyperlink.Delete does not work properly

  1. #1
    VBAX Newbie
    Joined
    Mar 2022
    Posts
    3
    Location

    Post VBA Hyperlink.Delete does not work properly

    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?

  2. #2
    VBAX Contributor
    Joined
    Jul 2020
    Location
    Sun Prairie
    Posts
    123
    Location
    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
    Last edited by Chas Kenyon; 03-16-2022 at 10:37 AM.

  3. #3
    VBAX Contributor
    Joined
    Jul 2020
    Location
    Sun Prairie
    Posts
    123
    Location
    Cross-posted at https://www.msofficeforums.com/word-...-properly.html.

    For cross-posting etiquette, please read: A Message to Forum Cross-Posters

  4. #4
    VBAX Newbie
    Joined
    Mar 2022
    Posts
    3
    Location
    Thank you, it worked!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •