我正在编写一个Excel宏,它打开Word文档并按名称查找CommandButton对象。当它找到对象时,它会尝试检查它是否有与之关联的图片。它似乎是定位对象,但当我尝试引用图片的句柄时死于“灾难性”死亡。之前我已经完成了这个并且想看看图片的句柄是否为零对我有用。不确定这里有什么,也许别人可以看到我错过的东西?
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
答案 0 :(得分:0)
我能够在没有问题的情况下实现这一功能。您可能需要单步执行代码以查看文档是否先完全加载。
以下是为我工作的代码,经过编辑以匹配原始问题的格式。
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
如果您仍然收到该错误,我认为这可能与图片未完全加载有关。如果是这样,我会添加一些错误处理来捕获该错误,并在稍后处理重试以查看图片的句柄是否可用。
这是我运行该代码时得到的结果:
答案 1 :(得分:0)
必须弄清楚如何运行公共函数,但这很容易。谢谢你的反馈,Ryan。仍然不确定为什么你的工作而我的工作没有,但至少我绕过它。