无法在 Excel 中处理 Word 命令按钮对象

Can't work on Word CommandButton object from within Excel

我正在编写一个 Excel 宏,它可以打开 Word 文档并按名称查找命令按钮对象。当它找到对象时,它会尝试检查它是否有与之关联的图片。它似乎在定位对象,但是当我尝试引用图片的句柄时死于 "catastrophic" 死亡。我以前做过这个,看看图片的句柄是否为零对我有用。不确定这里有什么,也许其他人可以看到我遗漏了什么?

Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(strFileName)
objWord.Visible = True

Set cmdSignatureButton = fncGetCommandButtonByName("NameOfCommandButtonImLookingFor", objDoc)
MsgBox "h=" & cmdSignatureButton.Picture.Handle
' It dies here, giving the error: 
'   Runtime error -2147418113 (8000ffff)
'   Automation error
'   Catastrophic failure



Private Function fncGetCommandButtonByName(strName As String, objDoc As Word.Document)
    Dim obj As Object
    Dim i As Integer

    For i = objDoc.InlineShapes.Count To 1 Step -1
        With objDoc.InlineShapes(i)
            If .Type = 5 Then
                If .OLEFormat.Object.Name = strName Then
                    Set fncGetCommandButtonByName = .OLEFormat.Object
    MsgBox "Found the Command Button object"        ' Seems to find the CommandButton object here
                    Exit Function
                End If
            End If
        End With
    Next
End Function

我能够毫无问题地运行此功能。您可能需要单步执行代码以先查看文档是否已完全加载。

这是对我有用的代码,经过编辑以匹配所提出的原始问题的格式。

    Dim objWord As Object: Set objWord = CreateObject("Word.Application")
    Dim objDoc  As Object: Set objDoc = objWord.Documents.Open(strFileName)

    objWord.Visible = True
    Dim cmdSignatureButton As Object

    Set cmdSignatureButton = fncGetCommandButtonByName("CommandButton1", objDoc)

    If Not cmdSignatureButton Is Nothing Then
        'Do something when it isn't nothing
        MsgBox "h=" & cmdSignatureButton.Picture.Handle
    Else
        'Something here
    End If

Private Function fncGetCommandButtonByName(strName As String, objDoc As Word.Document) As Object
    Dim i As Integer

    For i = objDoc.InlineShapes.Count To 1 Step -1
        With objDoc.InlineShapes(i)
            If .Type = 5 Then
                If .OLEFormat.Object.Name = strName Then
                    Set fncGetCommandButtonByName = .OLEFormat.Object
                    Exit Function
                End If
            End If
        End With
    Next

    Set fncGetCommandButtonByName = Nothing 'set it equal to nothing when it fails
End Function

如果您仍然收到该错误,我认为这可能与图片未完全加载有关。如果是这样,我会添加一些错误处理来捕获该错误并稍后处理重试以查看图片的句柄是否可用。

这是我 运行 代码时得到的结果:

好的,我想我至少有办法了。我继续我的下一个问题,它非常相似。在本例中,我在 Excel 电子表格的命令按钮中查找图像,但我是从 Access 中这样做的。我没有尝试越过障碍让 Access VBA 询问 Excel 文件,而是将 Public 函数放入 Access 调用的 Excel 文件中。 Excel 检查图像按钮没有问题,所以它只是 returns 我的答案。

必须弄清楚如何 运行 Public 函数,但这很容易。感谢您的反馈,瑞安。仍然不确定为什么你的有效而我的无效,但至少我绕过了它。