【发布时间】:2019-07-20 00:47:24
【问题描述】:
我有两个 Word 文档,每个文档都包含一个单词。 我有第三个文档,需要从两个文档中提取每个单词并使用替换功能编辑文档中的所有超链接。 如果我在函数中输入一个字符串,replace 函数会起作用,但如果尝试从文档中提取两个单词,则替换函数不起作用
Public Sub Document_Open()
Dim x As Document
Set newSource = Application.Documents.Open("\\t1dc\Everyone\Ben\ns.docx", ReadOnly:=True, Visible:=False)
Set oldSource = Application.Documents.Open("\\t1dc\Everyone\Ben\os.docx", ReadOnly:=True, Visible:=False)
Dim newServer As Range
Set newServer = newSource.Content
'Test using message box
MsgBox newServer
Dim oldServer As Range
Set oldServer = oldSource.Content
'Test using message box
MsgBox oldServer
For Each h In ActiveDocument.Hyperlinks
h.Address = Replace(h.Address, oldServer.Text, newServer.Text)
MsgBox h.Address
Next
newSource.Close
oldSource.Close
Set x = Nothing
End Sub
【问题讨论】:
-
我没有在问题中看到“替换功能”。您需要包含所有相关信息(minimal reproducible example),以便人们可以重现该情况。还要描述“它不起作用”的含义——这不是一个准确的问题描述。最佳猜测:
ActiveDocument不是您认为的文件。也为该文档创建一个对象,并在打开其他文档之前分配它。 -
对不起第一次发帖。在 For Each 循环中调用 replace 函数。如果我使用消息框来显示变量 oldServer 和 newServer,它会显示包含在我从中提取的文档中的文本。但是,替换函数似乎无法读取变量 oldServer 或 newServer。但是如果我在替换函数参数中输入一个字符串,例如“server1”,该函数可以正常工作并进行字符串替换。