0

After a Paste special linking of a range of cells from Excel to Word (2013) the field looks like this:

{ LINK Excel.Sheet.12 "D:\\RelativePath\\1\\work\\tmp.xlsx" Sheet1!NamedRange \a \p }

If you move the source (.xlsx) and receiver (.docx) to the 2 folder, you need to change the link in the LINK field so that it looks like this:

{ LINK Excel.Sheet.12 "D:\\RelativePath\\2\\work\\tmp.xlsx" Sheet1!NamedRange \a \p }

When there are many such fields, it is inconvenient.

I tried both this:

{ LINK Excel.Sheet.12 "...\\...\\work\\tmp.xlsx" Sheet1!NamedRange \a \p }

and that:

{ LINK Excel.Sheet.12 "~\\work\\tmp.xlsx" Sheet1!NamedRange \a \p } but nothing works.

That doesn't work either:

How to create absolute hyperlinks and relative hyperlinks in Word documents

Is it possible to specify in the LINK field not absolute, but relative source address?

Upd @Cindy Meister suggested a solution and after some refinement the code works fine.

Here he is:

Sub updateLINKs()
Dim doc As Word.Document
Dim fld As Word.Field
Dim sFilePath As String, sFileName As String
Set doc = ActiveDocument
sFilePath = doc.Path
For Each fld In doc.Fields
    If fld.Type = wdFieldLink Then
      If fld.Result.InlineShapes.Count > 0 And _
         InStr(fld.OLEFormat.ClassType, "Excel") And _
         fld.LinkFormat.SourcePath <> sFilePath Then
           sFileName = fld.LinkFormat.SourceName
           fld.LinkFormat.SourceFullName = sFilePath & "\" & sFileName
      End If
    End If
Next
End Sub
4

2 回答 2

0

不能在Link字段中使用相对路径。需要在字段代码中更新/更改路径。这可以通过使用LinkFormat属性提供的可能性以合理直接的方式完成。

例如,假设相对路径与 Word 文档的路径相同,则以下代码:

  1. Document.Path属性中获取路径
  2. 循环文档中的所有字段并确定它们是否是来自显示InlineShape(对象,而不是文本)的 Excel 源的 LINK 字段。这些字段以相反的顺序循环,因为更改路径会导致 Word 在后台删除并重新创建 LINK。这意味着从文档开头开始的循环将重复“命中”同一字段,从而导致无限循环。
  3. Link使用字段确定链接对象的当前文件名LinkFormat.SourceName
  4. 连接信息并将其分配给LinkFormat.SourceFullName属性

请注意LinkFormat.SourcePathLinkFormat.SourceName属性是只读的,因此只能使用 更改路径SourceFullName

Sub UpdateLinks()
    Dim doc As Word.Document
    Dim fld As Word.Field, nrFields As Long, i As Long
    Dim sFilePath As String, sFileName As String

    Set doc = ActiveDocument
    sFilePath = doc.path
    nrFields = doc.Fields.Count
    For i = nrFields To 1 Step -1
        Set fld = doc.Fields(i)
        If fld.Type = wdFieldLink Then
          If fld.result.InlineShapes.Count > 0 And _
             InStr(fld.OleFormat.ClassType, "Excel") Then
               sFileName = fld.LinkFormat.SourceName
               fld.LinkFormat.SourceFullName = sFilePath & "\" & sFileName
          End If
        End If
    Next
End Sub
于 2018-12-30T18:41:13.573 回答
0

不能在 LINK 字段中指定相对路径。这需要在 LINK 字段中嵌入另一个字段,但正如我之前所说,您不能使用 LINK 字段来执行此操作。您发布的链接仅涉及超链接的超链接基础设置,这也不会产生真正的相对链接。

LINK 字段的唯一解决方法是使用更新绝对路径的宏。

于 2018-12-30T12:07:30.457 回答