使用VBA编辑链接时如何防止链接格式化更改?

时间:2013-12-20 14:59:05

标签: vba ms-publisher

我目前正在使用以下代码更新应用程序中的所有链接:

Sub AddSources()
    Dim pubPage As Page
    Dim pubShape As Shape
    Dim hprlink As Hyperlink
    Dim origAddress() As String
    Dim exportFileName As String
    exportFileName = "TestResume"
    Dim linkSource As String
    linkSource = "TestSource2"

    For Each pubPage In ActiveDocument.Pages
        For Each pubShape In pubPage.Shapes
            If pubShape.Type = pbTextFrame Then
                For Each hprlink In pubShape.TextFrame.TextRange.Hyperlinks
                    If InStr(hprlink.Address, "http://bleaney.ca") > 0 Then
                        origAddress = Split(hprlink.Address, "?source=")
                        hprlink.Address = origAddress(0) + "?source=" + linkSource
                    End If
                Next hprlink
            End If
        Next pubShape
    Next pubPage
    ThisDocument.ExportAsFixedFormat pbFixedFormatTypePDF, "C:\" + exportFileName + ".pdf"
End Sub

问题在于,当我更新链接时,它们会丢失格式。如何保留超链接的格式?我尝试查看Copy and Paste方法,但看起来我真正需要的是Paste Special,它不存在于Hyperlink对象的Range属性上。

1 个答案:

答案 0 :(得分:0)

尝试添加以下行以捕获颜色和下划线,然后在地址更改后将其设置回来

Sub AddSources()
    Dim pubPage As Page
    Dim pubShape As Shape
    Dim hprlink As Hyperlink
    Dim origAddress() As String
    Dim exportFileName As String
      Dim undline AS Long
      Dim clr AS Long
    exportFileName = "TestResume"
    Dim linkSource As String
    linkSource = "TestSource2"

    For Each pubPage In ActiveDocument.Pages
        For Each pubShape In pubPage.Shapes
            If pubShape.Type = pbTextFrame Then
                For Each hprlink In pubShape.TextFrame.TextRange.Hyperlinks
                    If InStr(hprlink.Address, "http://bleaney.ca") > 0 Then
                        undline = hprlink.Range.Font.Underline
                        clr = hprlink.Range.Font.Color
                        origAddress = Split(hprlink.Address, "?source=")
                        hprlink.Address = origAddress(0) + "?source=" + linkSource
                        hprlink.Range.Font.Color = clr
                        hprlink.Range.Font.Underline = undline
                    End If
                Next hprlink
            End If
         Next pubShape
    Next pubPage
    ThisDocument.ExportAsFixedFormat pbFixedFormatTypePDF, "C:\" + exportFileName + ".pdf"
End Sub