【问题标题】:How can I find and replace text in Word using Excel VBA?如何使用 Excel VBA 在 Word 中查找和替换文本?
【发布时间】:2019-08-23 17:51:08
【问题描述】:

我正在使用 Excel VBA 在 Word 中打开文档。打开文档后,目标是搜索“InsuranceCompanyName”并将其替换为公司名称。

我试过了

wordDoc.Find.Execute FindText:="InsuranceCompanyName", ReplaceWith:="Fake Ins Co"

wordDoc.Replace What:="InsuranceCompanyName", Replacement:="Fake Ins Co"

还有

For Each myStoryRange In ActiveDocument.StoryRanges

    With myStoryRange.Find
        .Text = "InsuranceCompanyName"
        .Replacement.Text = "Fake Ins Co"
        .WrapText = wdFindContinue
        .Execute Replace:=wdReplaceAll
    End With 
Next myStoryRange

下面列出了完整的代码。

Sub FindReplace()

Dim wordApp As Object 
Dim wordDoc As Object 
Dim myStoryRange As Range

'sets up the word app
Set wordApp = CreateObject("Word.Application")
wordApp.Visible = True 

'opens the document that we need to search through 
Set wordDoc = wordDoc = wordApp.Documents.Open("C:\Users\cd\LEQdoc.docx")

'here is where the find and replace code would go

End Sub 

对于第一种方法,我得到了错误:

对象不支持此属性或方法。

第二个:同样的错误

第三种方法:

参数不是可选的

关于.Find in

With myStoryRange.Find

【问题讨论】:

  • Set wordDoc = wordDoc = wordApp.Documents.Open("C:\Users\cd\LEQdoc.docx") 应该是Set wordDoc = wordApp.Documents.Open("C:\Users\cd\LEQdoc.docx")
  • ActiveDocument 不是 Excel 概念,因此您需要在前面加上 wordAppwordApp.ActiveDocument
  • 还要确保声明常量 wdFindContinuewdReplaceAll 等,因为您是后期绑定 MS Word
  • @SiddharthRout - 快!
  • Dim myStoryRange As Range 更改为 Dim myStoryRange As Object

标签: excel vba ms-word


【解决方案1】:

试试这个代码

Option Explicit

Const wdReplaceAll = 2

Sub FindReplace()
    Dim wordApp As Object
    Dim wordDoc As Object
    Dim myStoryRange As Object

    '~~> Sets up the word app
    Set wordApp = CreateObject("Word.Application")
    wordApp.Visible = True

    '~~> Opens the document that we need to search through
    Set wordDoc = wordApp.Documents.Open("C:\Users\routs\Desktop\Sample.docx")

    For Each myStoryRange In wordDoc.StoryRanges
        With myStoryRange.Find
            .Text = "InsuranceCompanyName"
            .Replacement.Text = "Fake Ins Co"
            .Execute Replace:=wdReplaceAll
        End With
    Next myStoryRange
End Sub

行动中

【讨论】:

  • 这太棒了!它不再挂在那条线上并继续通过它。但是,它实际上并没有替换它应该查找和替换的文本。
  • 我已经添加了截图。您可能需要刷新页面才能看到它
  • 顺便说一句,我希望您在代码顶部声明 Const wdReplaceAll = 2 ;)?
  • 完美运行!谢谢您的帮助。总是非常感谢。
猜你喜欢
  • 2014-10-12
  • 2019-08-27
  • 2021-10-13
  • 2019-05-20
  • 2018-01-18
  • 2019-10-23
  • 2021-04-27
  • 2017-08-06
  • 2018-11-11
相关资源
最近更新 更多