Vba 向链接的图像添加超链接

Vba 向链接的图像添加超链接,vba,ms-office,ms-word,Vba,Ms Office,Ms Word,我正在尝试向图像添加超链接,这些超链接是通过IncludePicture字段添加的 例如,这是一个图像: { IncludePicture "C:\\Test\\Image 1.png" \d } 因此,应向其添加超链接: C:\\Test\\Image 1.png 之后,我可以用鼠标点击文档中的图像,它将在文件管理器中打开 这是代码。由于某种原因,它不能正常工作。应该如何修复 Sub AddHyperlinksToImages() On Error Resume Next

我正在尝试向图像添加超链接,这些超链接是通过IncludePicture字段添加的

例如,这是一个图像:

{ IncludePicture "C:\\Test\\Image 1.png" \d }
因此,应向其添加超链接:

C:\\Test\\Image 1.png
之后,我可以用鼠标点击文档中的图像,它将在文件管理器中打开

这是代码。由于某种原因,它不能正常工作。应该如何修复

Sub AddHyperlinksToImages()
    On Error Resume Next
    Application.ScreenUpdating = False
    Dim iShp As InlineShape
    For Each iShp In ActiveDocument.InlineShapes
        iShp.Hyperlink.Address = iShp.LinkFormat.SourceFullName 'Doesn't work

        'Just for testing
        'fullPath = iShp.LinkFormat.SourceFullName
        'MsgBox fullPath
    Next
    Application.ScreenUpdating = True
End Sub
请尝试此代码

Sub AddHyperlinksToImages()
    ' 22 Sep 2017

    Dim Fld As Field
    Dim FilePath As String
    Dim Tmp As String
    Dim i As Integer

    Application.ScreenUpdating = False
    ActiveDocument.Fields.Update
    For Each Fld In ActiveDocument.Fields
        With Fld
            If InStr(1, Trim(.Code), "includepicture", vbTextCompare) = 1 Then
                If .InlineShape.Hyperlink Is Nothing Then
                    i = InStr(.Code, Chr(34))
                    If i Then
                        FilePath = Replace(Mid(.Code, i + 1), "\\", "\")
                        i = InStr(FilePath, "\*")
                        If i Then FilePath = Left(FilePath, i - 1)
                        Do While Len(FilePath) > 1
                            i = Asc(Right(FilePath, 1))
                            FilePath = Left(FilePath, Len(FilePath) - 1)
                            If i = 34 Then Exit Do
                        Loop
                        If i > 1 Then ActiveDocument.Hyperlinks.Add .InlineShape, FilePath
                    End If
                End If
            End If
        End With
    Next Fld
    Application.ScreenUpdating = True
End Sub

谢谢它部分有效。目前我正试图以某种方式修复它。有几个问题:1如果我打开一个文档并启动宏,它会给我一个错误。为避免此错误,必须更新图像,即首先打开文档,然后按Ctrl-a,然后按F9,然后启动宏。这样,脚本将在没有错误的情况下启动。2超链接有点断开,因为2.1如果路径包含空格,某些字母会被修剪;2.2由于某种原因,\\in path变为\\\\。据我所知,使用FilePath=splittrimplace.Code,,%201可以解决空间问题。但它不起作用。这有点奇怪,因为类似FilePath=splittrimplace.Code、img、img%201这样的东西可以正常工作。您可以添加代码来更新字段。我认为它类似于ActiveDocument.Fields.Update,可能会添加到过程的开头。我的代码只是复制在字段中找到的路径,并在创建超链接时使用它。Replace.Code.针对路径名前后的双行距字插入。如果文件名本身可能有双空格,则可能需要另一种方法。%20没有用处,除非它包含在提取的文件路径中,在这种情况下,您不需要知道它。在将路径分配给超链接之前,先查明路径是否已损坏。我对代码做了一些改进。请看一看。