如何打开(并保存)Word文档中的所有嵌入文档?

时间:2014-03-22 22:10:35

标签: vba error-handling reference word-vba

我正在寻找VBA来保存Word文档中的嵌入文件。但我打开它们时遇到了问题:

Sub Extract()

    Dim num as Integer

    Dim numObjects As Integer
    numObjects = ActiveDocument.InlineShapes.count

    MsgBox numObjects  ' prints "11"

    For num = 1 To numObjects    
        If ActiveDocument.InlineShapes(num).Type = 1 Then
            'it's an embedded OLE type so open it.            
            ActiveDocument.InlineShapes(num).OLEFormat.Open

            'Works for the first one but errors 5941 (the requested
            '  member of the collection does not exist) 
        End If
    Next num

End Sub

此代码打开第一个嵌入文件(如果尚未打开)。它在下一个错误。

或者,如果第一个文件已经打开,宏似乎什么都不做。

任何提示? (我正在使用Word 2010执行此操作。)

1 个答案:

答案 0 :(得分:1)

答案似乎很简单 - 在您打开第一个嵌入文件后,当您尝试打开下一个引用活动文档的嵌入对象而不是所需的嵌入对象时,它会变为活动状态。以这种方式尝试使用对象变量:

Sub Extract()

    Dim num as Integer
    Dim AD as document
    Set AD = activedocument

    Dim numObjects As Integer
    numObjects = AD.InlineShapes.count

    MsgBox numObjects  ' prints "11"

    For num = 1 To numObjects    
        If AD.InlineShapes(num).Type = 1 Then
            'it's an embedded OLE type so open it.            
            AD.InlineShapes(num).OLEFormat.Open

        End If
    Next num

End Sub