透過VBA更新Microsoft Word連結項

透過VBA更新Microsoft Word連結項

是否可以更改物品MS Word 中的連結實用地透過使用 VBA 來引用 Excel 電子表格?

我發現了關於如何更改文件來源,但不是物品,如下圖所示編輯連結MS Word 2010 的選單:

編輯連結標籤

完全相同的問題已經被問過這裡,但沒有任何答案,大約兩年前。我也調查過連結格式屬性文檔,用於編輯連結的源代碼,但我無處可去。

任何有關如何解決該問題的想法都將受到讚賞。

背景:我有一個 Excel 電子表格,為 Word 文件提供資料。我正在嘗試使用此文件作為模板,根據分析,我將更改將資料輸入到 Word 文件的電子表格。電子表格中的表格(未依此格式格式化)的範圍可能有所不同。但是,它們具有相同數量的列。由於行數不同,我必須相應地更改 Item 欄位。

編輯

我提供了 2 個範例檔案作為該問題的 MWE。他們可以找到這裡

答案1

我找到了解決這個問題的方法。而不是改變伊滕斯,我建立了一個 VBA 腳本來命名所有連結的範圍。因此,我沒有更改 Word 中的連結項,而是更改了 excel 中的命名範圍值。連結項保持不變,但它指向可以實際修改的範圍。這是我整理的用於將名稱放入範圍的程式碼:

Sub CreateNamedRanges()

Dim i As Integer
For i = 1 To Worksheets.Count
     sheetName = "Mysheet" & i
     varName = "Myvar" & CStr(i)
     Set Rng = Sheets(sheetName).Range("G6:I9")
     ActiveWorkbook.Names.Add Name:=varName, RefersTo:=Rng
Next i

End Sub

這種方法的缺點是我必須手動重新建立(連結)之前所做的所有連接。為了更改文件來源,我使用了問題連結中的程式碼。為了完整起見,我將其寫在這裡:

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

最後,一次更新所有連結:

Sub AutoOpen()
    ActiveDocument.Fields.Update
End Sub

相關內容