在 Excel VBA 的嵌入式 Word 文档中使用 find/replace 方法时出错

Error when using find/replace method in an embedded Word document in Excel VBA

我的工作表中有一个嵌入的 word 文档,名称 "Rec1"

所以之前使用:

Sub ReplaceTextinOLEObject
    Dim oDoc As OLEObject
    Set oDoc = Worksheets("Sheet1").OLEObjects("Rec1")
    oDoc.Activate
    With oDoc.Content.Find
        .ClearFormatting
        .Text = "hi"
        .Replacement.ClearFormatting
        .Replacement.Text = "hello"
        .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
    End With
    Word.Application.Quit wdDoNotSaveChanges
End Sub

执行上述运行时,With部分出现以下错误:

Run-time error '438':
object doesn't support this property or method

OLE 嵌入 word 文档使用 Find 对象有什么问题?

这里的问题是 OLEObjects 没有 .Content 属性。这也是错误告诉你的内容。

因此您必须改用 oDoc.Object.Content.Find。而且你不需要 oDoc.Activate 文件,没有它也可以工作。

以下应该有效:

Public Sub ReplaceTextinOLEObject
    Dim oDoc As OLEObject
    Set oDoc = Worksheets("Sheet1").OLEObjects("Rec1")
    'oDoc.Activate 'remove this line, activate is not needed here
    With oDoc.Object.Content.Find
        .ClearFormatting
        .Text = "hi"
        .Replacement.ClearFormatting
        .Replacement.Text = "hello"
        .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
    End With
    Word.Application.Quit wdDoNotSaveChanges
End Sub

注:当然"Microsoft Word 16.0 Object Library"(版本可能不同)需要参考运行这段代码