首页 > 解决方案 > 如何使用 Excel VBA 在 Word 中查找和替换文本?

问题描述

我正在使用 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

标签: excelvbams-word

解决方案


试试这个代码

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

在行动

在此处输入图像描述


推荐阅读