我有一批嵌入了 Excel 工作表的 Word 文档。用户通过双击工作表图像并打开嵌入的 Excel 对象在 Excel 工作表中输入数据。我需要获取用户输入的数据。
下面是 WORD VBA,其中引用了 Microsoft Excel 15 库。 (Word 和 Excel 对象是在 Office 2010 下创建的。)
我可以找到 OLE 对象,但无法用它做任何事情。在下面的代码中,我尝试将对象分配给工作表对象,但出现类型不匹配错误。
使事情进一步复杂化的是嵌入的 Excel 工作表具有宏。在解决该问题的某些过程中,会打开一个 Excel 窗口,并提示启用宏安全提示。我很可能可以暂时禁用宏检查来解决这个问题。
我所需要做的就是获取工作表中的数据,然后将其复制到其他地方。如果可能的话,我很乐意将工作表复制到外部文件。
我手头有 Office 2010 和 2013,以及 Visual Studio 2010 Pro 和 2014 Express。
如何获取嵌入的工作表数据?
Sub x()
Dim oWS As Excel.Worksheet
Dim oIShape As InlineShape
For Each oIShape In ActiveDocument.InlineShapes
If Not oIShape.OLEFormat Is Nothing Then
If InStr(1, oIShape.OLEFormat.ProgID, "Excel") Then
oIShape.OLEFormat.ActivateAs (oIShape.OLEFormat.ClassType) 'Excel.Sheet.8
Set oWS = oIShape '** type mismatch
Debug.Print oWS.Cells(1, 1)
End If
End If
Next oIShape
End Sub
我使用建议开始之前的尝试:通过VBA修改Word文档中嵌入的Excel工作簿 https://stackoverflow.com/questions/483813/modify-embedded-excel-workbook-in-word-document-via-vba
在正确的引用方面存在一些问题,并且代码弄乱了文档。
下面是另一遍,工作正常,但有一些问题和我不明白的代码。
1)我不想使用编辑模式,但其他模式不起作用
2)完美的引用 Set xlApp = GetObject(, "Excel.Application") 很奇怪。某种未记录的功能?
Sub TestMacro2()
Dim lNumShapes As Long
Dim lShapeCnt As Long
Dim xlApp As Object
Dim wrdActDoc As Document
Dim iRow As Integer
Dim iCol As Integer
Set wrdActDoc = ActiveDocument
For lShapeCnt = 1 To wrdActDoc.InlineShapes.Count
If wrdActDoc.InlineShapes(lShapeCnt).Type = wdInlineShapeEmbeddedOLEObject Then
If wrdActDoc.InlineShapes(lShapeCnt).OLEFormat.ProgID = "Excel.Sheet.8" Then
wrdActDoc.InlineShapes(lShapeCnt).OLEFormat.Edit
Set xlApp = GetObject(, "Excel.Application")
With xlApp.Workbooks(1).Worksheets(2) ' can be multiple sheets, #2 is needed in this case
For iCol = 3 To .UsedRange.Columns.Count
If .Cells(1, iCol) = "" Then Exit For
For iRow = 1 To .UsedRange.Rows.Count
Debug.Print .Cells(iRow, iCol) & "; ";
Next iRow
Debug.Print 'line feed
Next iCol
End With
xlApp.Workbooks(1).Close
xlApp.Quit
Set xlApp = Nothing
End If
End If
Next lShapeCnt
End Sub
代码运行良好,足以完成我的提取任务 - 谢谢!