我正在编写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
答案 0 :(得分: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
答案 1 :(得分:2)
删除超链接的行已注释掉。以下行将删除所选范围内的第一个超链接:
Selection.Range.Hyperlinks(1).Delete
这也会使Selection.Range.Hyperlinks.Count
减1。
要查看链接计数的变化情况,您可以在文档上运行以下方法:
Sub AddAndRemoveHyperlink()
Dim oRange As Range
Set oRange = ActiveDocument.Range
oRange.Collapse wdCollapseStart
oRange.MoveEnd wdCharacter
Debug.Print ActiveDocument.Range.Hyperlinks.Count
ActiveDocument.Hyperlinks.Add oRange, "http://www.example.com"
Debug.Print ActiveDocument.Range.Hyperlinks.Count
ActiveDocument.Hyperlinks.Item(1).Delete
Debug.Print ActiveDocument.Range.Hyperlinks.Count
End Sub