如何从Microsoft Word文档中删除超链接?

1 vba listbox ms-word hyperlink

我正在编写VB宏来为我的工作做一些文档处理.搜索文本行,将括号内的文本放入列表(框)中.

当我想删除文档中的所有超链接然后生成新的超链接(不一定在原始超链接的位置)时,问题就来了

所以问题是如何删除现有的超链接?

我当前的问题是,每次添加链接时,超链接计数会增加一个,但是当您删除它时,计数不会减少.(因此我现在有一个包含32个链接的文档 - 除了我自己放入的3个文件外都是空的 - 它们没有显示在文档中)

在代码的最后是我尝试删除超链接.

Private Sub FindLinksV3_Click()

    ListOfLinks.Clear

    ListOfLinks.AddItem Now
    ListOfLinks.AddItem ("Test String 1")

    ListOfLinks.AddItem ActiveDocument.FullName

    SentenceCount = ActiveDocument.Sentences.Count
    ListOfLinks.AddItem ("Sentence Count:" & SentenceCount)
    counter = 0

    For Each myobject In ActiveDocument.Sentences    ' Iterate through each element.
        ListOfLinks.AddItem myobject
        counter = counter + 1

        BracketStart = (InStr(1, myobject, "("))

        If BracketStart > 0 Then
            BracketStop = (InStr(1, myobject, ")"))

            If BracketStop > 0 Then
                ListOfLinks.AddItem Mid$(myobject, BracketStart + 1, BracketStop - BracketStart - 1)

                ActiveDocument.Sentences(counter).Select

                ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:= _
                "http://testnolink/" & counter, ScreenTip:=""  'TextToDisplay:=""

            End If
        End If
    Next

    'ActiveDocument.Sentences(1).Select
    '
    'Selection.Range.Hyperlinks(1).Delete

    ActiveDocument.Hyperlinks.Item(1).Delete

    Debug.Print ActiveDocument.Hyperlinks.Count

End Sub
Run Code Online (Sandbox Code Playgroud)

小智 5

这是一个旧帖子,所以我添加这个VBA代码,以防它对某人有用.

需要以相反的顺序删除超链接(集合):

Sub RemoveHyperlinksInDoc()
    ' You need to delete collection members starting from the end going backwards
    With ActiveDocument
        For i = .Hyperlinks.Count To 1 Step -1
            .Hyperlinks(i).Delete
        Next
    End With 
End Sub

Sub RemoveHyperlinksInRange()
    ' You need to delete collection members starting from the end going backwards
    With Selection.Range
        For i = .Hyperlinks.Count To 1 Step -1
            .Hyperlinks(i).Delete
        Next
    End With    
End Sub
Run Code Online (Sandbox Code Playgroud)