如何使用VBA更改Word中的链接位置?

时间:2015-12-24 23:28:46

标签: vba ms-word word-vba

我的Word文档包含指向Excel的链接,在显示时,如下所示:

{LINK Excel.SheetMacroEnabled.12“C:\\ Users \\ Shawn \\ projects \\ Workbook1.xlsm”“Range1”}

我需要我的宏才能将其更改为新的路径/文件:

strNewFile = "C:\Users\Shawn\OtherFolder\Workbook2.xlsm".  

(注意单个反斜杠与双反斜杠。)

最简单的方法是什么? (使用Word 2013)

2 个答案:

答案 0 :(得分:1)

Sub changeSource()

Dim dlgSelectFile As FileDialog  'FileDialog object
Dim thisField As Field
Dim selectedFile As Variant    'must be Variant to contain filepath of selected item
Dim newFile As Variant
Dim fieldCount As Integer



'create FileDialog object as File Picker dialog box
Set dlgSelectFile = Application.FileDialog(FileDialogType:=msoFileDialogFilePicker)



With dlgSelectFile
'use Show method to display File Picker dialog box and return user's action
    If .Show = -1 Then

        'step through each string in the FileDialogSelectedItems collection
        For Each selectedFile In .SelectedItems
            newFile = selectedFile    'gets new filepath
        Next selectedFile
    Else   'user clicked cancel
    End If
End With
Set dlgSelectFile = Nothing



'update fields
fieldCount = ActiveDocument.Fields.Count
For x = 1 To fieldCount
    ActiveDocument.Fields(x).LinkFormat.SourceFullName = newFile
Next x

End Sub

答案 1 :(得分:0)

这篇文章似乎有答案: Linked Table in MS Word

使用此代码:

Dim fieldCount As Integer, x As Long
With ActiveDocument
  fieldCount = .Fields.Count
  For x = 1 To fieldCount
    With .Fields(x)
      If .Type = 56 Then
        'only update Excel links. Type 56 is an excel link
        Debug.Print .LinkFormat.SourceFullName
        .LinkFormat.SourceFullName = newfile '
        .Update
        .LinkFormat.AutoUpdate = False
        DoEvents
      End If
    End With
  Next x
End With