[英]Changing links in word doc from excel macro
我在一個 excel 宏中有此代碼,該宏旨在更新我的 Word 文檔中的鏈接。 每個季度,我都會在 excel 中運行一個宏,該宏鏈接到需要從上一季度更新到當前季度的 12 字文檔。
OldFilePath 是最后一個季度的 excel 工作簿位置,NewFilePath 是當前季度的 excel 工作簿位置,我的 word 文檔的位置在單元格 (c,33) 中。
我已成功更新第一個單詞 doc,但我的宏在更新第二個單詞 doc 鏈接時崩潰。 我收到一條錯誤消息“運行時錯誤‘91’:對象變量或塊變量未設置”
感謝您幫助解決此問題。 謝謝。
編輯:事實證明,我在 word 文件中有某種“幽靈鏈接”。 當宏運行時,它會計算 13 個要更新的鏈接,但是當我查看 word doc 的編輯鏈接部分中的鏈接時,我只計算了 12 個。以前有人見過這個嗎?
Sub UpdateWordLinks()
Dim wordApp As Word.Application
Dim wDoc As Word.Document
oldFilePath = Range("AG17")
newFilePath = Range("AG18")
c = 3
Do Until c > 12
Root = Cells(c, 33)
Set wordApp = CreateObject("word.application")
Set wDoc = wordApp.Documents.Open(Root)
wordApp.Visible = True
'Use Replace to change the oldFilePath to the newFilePath on the Field code
i = 1
For i = 1 To wDoc.Fields.Count
wDoc.Fields(i).LinkFormat.SourceFullName = Replace(wDoc.Fields(i).LinkFormat.SourceFullName, oldFilePath, newFilePath)
Next i
'Update the links
wDoc.Fields.Update
wordApp.Documents.Save
wordApp.Documents.Close
wordApp.Quit
c = c + 1
Loop
End Sub
解決了問題 - 我決定編寫一個類似於手動執行 alt+f9、查找和替換鏈接、刷新鏈接的宏,而不是通過“編輯鏈接”功能編輯鏈接。
Sub UpdateWordLinks()
Dim wordApp As Word.Application
Dim wDoc As Word.Document
oldFilePath = Range("AG17")
newFilePath = Range("AG18")
c = 3
Do Until c > 12
Root = Cells(c, 33)
Set wordApp = CreateObject("word.application")
Set wDoc = wordApp.Documents.Open(Root)
wordApp.Visible = True
'Use Replace to change the oldFilePath to the newFilePath on the Field code
wDoc.Fields.ToggleShowCodes
With wDoc.Content.Find
.Execute Findtext:=oldFilePath, Replacewith:=newFilePath, Format:=True, Replace:=wdReplaceAll
End With
wDoc.Fields.ToggleShowCodes
wDoc.Fields.Update
wDoc.Save
wDoc.Close
wordApp.Quit
c = c + 1
Loop
wordApp.Quit
End Sub
問題解決了。 如果在編輯鏈接部分找到的鏈接數量與單詞 doc 不同,則無關緊要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.