【问题标题】:How to get text from a Word document into another Word Document如何将Word文档中的文本导入另一个Word文档
【发布时间】: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”,该函数可以正常工作并进行字符串替换。

标签: vba ms-word


【解决方案1】:

检查 oldServer 和 newServer 的长度,因为您还拉入了位于行尾的 \r

【讨论】:

    【解决方案2】:

    好的,谢谢!

    从字符串的末尾删除,它可以工作

    将 oldS 变暗为字符串 oldS = Left(oldServer.Text, Len(oldServer.Text) - 1)

    【讨论】: