从excel宏更改word文档中的链接
我在excel宏中有此代码,用于更新word文档中的链接。每个季度,我都会在excel中运行一个宏,该宏链接到需要从上一季度更新到当前季度的12个word文档 OldFilePath是最后一个季度的excel工作簿位置,NewFilePath是当前季度的excel工作簿位置,my word文档的位置在单元格中(c,33) 我成功地更新了第一个word文档,但我的宏在更新第二个word文档链接时崩溃。我收到一条错误消息“运行时错误'91':未设置对象变量或With block变量” 我感谢你在解决这个问题上的帮助。谢谢 编辑:事实证明,我在word文件中有某种“鬼链接”。当宏运行时,它统计13个要更新的链接,但当我在word文档的“编辑链接”部分查看链接时,我只统计12个。以前有人见过这个吗从excel宏更改word文档中的链接,excel,vba,ms-word,Excel,Vba,Ms Word,我在excel宏中有此代码,用于更新word文档中的链接。每个季度,我都会在excel中运行一个宏,该宏链接到需要从上一季度更新到当前季度的12个word文档 OldFilePath是最后一个季度的excel工作簿位置,NewFilePath是当前季度的excel工作簿位置,my word文档的位置在单元格中(c,33) 我成功地更新了第一个word文档,但我的宏在更新第二个word文档链接时崩溃。我收到一条错误消息“运行时错误'91':未设置对象变量或With block变量” 我感谢你在解决
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
问题解决了。“编辑链接”部分中的链接数与word doc中的链接数不一样并不重要。文本框、页眉/页脚等中可能有链接。您的代码找不到这些链接。