VBA获取word文档中的所有超链接

时间:2013-09-26 17:47:39

标签: vba hyperlink ms-word

我正在尝试使用Visual Basic使用宏更新word文档中的所有超链接。我的代码仅更新不在文本框内的超链接,并且内部的超链接不会更改。如何更改所有超链接,包括任何文本框内的超链接? 我使用此代码来获取我的超链接:

 Sub UpdateLinks()
  Dim oLink As Hyperlink
  links = 0
  For Each oLink In ActiveDocument.Hyperlinks
    oLink.Range.Bold = 0
    oLink.Range.Italic = 0
    oLink.Range.Underline = wdUnderlineNone
    oLink.Range.Font.Color = wdColorWhite
    oLink.Range.Shading.BackgroundPatternColor = wdColorGray375
    links = links + 1
  Next oLink
 End Sub

1 个答案:

答案 0 :(得分:5)

这应该适合你:

Dim links As Integer
Sub UpdateLinks()
    links = 0
    UpdateDocLinks
    UpdateTextBoxLinks
End Sub
Sub UpdateDocLinks() 
    Dim oLink As Hyperlink
    For Each oLink In ActiveDocument.Hyperlinks
      links = links + FormatLink(oLink)
    Next oLink
End Sub
Sub UpdateTextBoxLinks()
    Dim i As Integer
    Dim oLink As Hyperlink
    For i = 1 To ActiveDocument.Shapes.Count
        ActiveDocument.Shapes(i).Select
        For Each oLink In Selection.Hyperlinks
            links = links + FormatLink(oLink)
        Next oLink
    Next i
End Sub

Function FormatLink(link As Hyperlink) As Integer
     With link.Range
         .Bold = 0
         .Italic = 0
         .Underline = wdUnderlineNone
         .Font.Color = wdColorWhite
         .Shading.BackgroundPatternColor = wdColorGray375
      End With
      FormatLink = 1
End Function

DRY版本

Dim links As Integer
Sub UpdateLinks()
    links = 0
    UpdateDocLinks
    UpdateTextBoxLinks
End Sub
Sub UpdateDocLinks()
    UpdateLinkSet ActiveDocument.Hyperlinks
End Sub
Sub UpdateTextBoxLinks()
    Dim i As Integer
    For i = 1 To ActiveDocument.Shapes.Count
        ActiveDocument.Shapes(i).Select
        UpdateLinkSet Selection.Hyperlinks
    Next i
End Sub
Sub UpdateLinkSet(link_set As Variant)
    Dim oLink As Hyperlink
    For Each oLink In link_set
        FormatLink oLink
    Next oLink
End Sub
Sub FormatLink(link As Hyperlink)
    With link.Range
       .Bold = 0
       .Italic = 0
       .Underline = wdUnderlineNone
       .Font.Color = wdColorWhite
       .Shading.BackgroundPatternColor = wdColorGray375
    End With
    links = links + 1
End Sub