【问题标题】:Execute Find and Replace function in an open Word document from Excel在 Excel 中打开的 Word 文档中执行查找和替换功能
【发布时间】:2016-11-05 15:05:26
【问题描述】:

我需要在 Excel 中打开一个 Word 文档(我成功了),然后(以编程方式)在该文档中执行查找/替换(没有成功)。

使用 Excel 宏的原因是替换文本取自一些 Excel 单元格。

Sub Word_find_replace_attempt_from_Excel()

    Set WordApp = CreateObject("Word.Application")
    WordApp.Visible = True
    Set WordDoc = WordApp.Documents.Open("C:\Test.doc") 'it exists already
    With WordDoc
        Find.Execute _
            FindText:="a", _
            ReplaceWith:="b", _
            Replace:=wdReplaceAll
    End with
End Sub

【问题讨论】:

标签: excel vba replace ms-word


【解决方案1】:

您不需要为 MS Word 设置引用,但请确保为您使用的任何 MS Word 枚举声明常量。

Sub Word_find_replace_attempt_from_Excel()
    Const wdReplaceAll = 2

    Set WordApp = CreateObject("Word.Application")
    WordApp.Visible = True

    Set WordDoc = WordApp.Documents.Open("C:\Test.doc")
    With WordDoc.Content.Find
        .Execute FindText:="a", ReplaceWith:="b", _
                 Format:=True, Replace:=wdReplaceAll, Forward:=True
    End With

End Sub

【讨论】:

  • 非常感谢亲爱的托马斯!你永远不会知道我是如何在上前询问之前花了两天时间谷歌搜索的。你的答案是正确的! :)
猜你喜欢
  • 2020-12-26
  • 2018-11-11
  • 2021-10-13
  • 1970-01-01
  • 2017-08-06
  • 2021-03-13
  • 2019-05-20
  • 1970-01-01
  • 2018-01-18
相关资源
最近更新 更多