【问题标题】:Error when using find/replace method in an embedded Word document in Excel VBA在 Excel VBA 的嵌入式 Word 文档中使用查找/替换方法时出错
【发布时间】:2018-09-06 16:46:33
【问题描述】:

我的工作表中有一个嵌入的 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 部分在下面提交错误:

运行时错误“438”:
对象不支持该属性或方法

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

【问题讨论】:

    标签: excel vba ms-word ole


    【解决方案1】:

    这里的问题是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 对象库”(版本可能有所不同)才能运行此代码。

    【讨论】:

      猜你喜欢
      • 2019-05-20
      • 2021-10-13
      • 2018-11-11
      • 2021-05-29
      • 1970-01-01
      • 2014-10-12
      • 1970-01-01
      • 2017-08-06
      • 2021-03-13
      相关资源
      最近更新 更多