简体   繁体   English

如何使用 Excel VBA 在 Word 中查找和替换文本?

[英]How can I find and replace text in Word using Excel VBA?

I am using Excel VBA to open a document in Word.我正在使用 Excel VBA 在 Word 中打开文档。 Once the document is open the goal is to search for "InsuranceCompanyName" and replace it with the company's name.打开文档后,目标是搜索“InsuranceCompanyName”并将其替换为公司名称。

I have tried我试过了

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

and

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

and also并且

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

The full code is listed below.下面列出了完整的代码。

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 

For the first method I get the error:对于第一种方法,我收到错误:

Object doesn't support this property or method.对象不支持此属性或方法。

For the second: the same error对于第二个:同样的错误

The third method:第三种方法:

argument not optional参数不是可选的

in regards to the .Find in关于 .Find in

With myStoryRange.Find

Try this code试试这个代码

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

In Action在行动

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM