Excel中的Word报告自动化来源编号

我需要通过从Excel中提取数字来自动进行报告。 我search并遵循源自http://www.makeuseof.com/tag/integrate-excel-data-word-document/的代码

代码无法正常运行,并遇到一些错误。 1. Excel未打开2.遇到运行时错误“438”:对象不支持此属性或方法。

我使用了网站build议的“早期绑定”代码,并且不工作,研究使用“后期绑定”。 仍然不起作用。 我插入“Microsoft Excel 14.0对象库”并在Word文档的“ActiveX控件”下插入“标签”

不知道出了什么问题。

当前的vba代码

Private Sub CommandButton1_Click() Dim objExcel As Object Set objExcel = CreateObject("Excel.Application") Set exWb = objExcel.Workbooks.Open("C:\Users\adong\Desktop\Reporting.xlsx") ThisDocument.DMY.Caption = exWb.Sheets("Summary").Cell(5, 4) exWb.Close Set exWb = Nothing End Sub 

先前的代码

 Private Sub CommandButton1_Click() Dim objExcel As New Excel.Application Dim exWb As Excel.Workbook Set exWb = objExcel.Workbooks.Open("C:\Users\adong\Desktop\Reporting.xlsx") ThisDocument.DMY.Caption = exWb.Sheets("Summary").Cells(5, 4) exWb.Close Set exWb = Nothing End Sub 

修改以下代码: https : //www.experts-exchange.com/questions/26874253/How-to-loop-with-VBA-on-all-controls-placed-in-a-Word-doc.html

您可以编写一个实用程序函数来获取ActiveX控件的名称和托pipe文档:

 Private Sub CommandButton1_Click() Dim con As Object Dim objExcel As Object, exWb As Object Set con = ActiveXControlByName(ThisDocument, "DMY") If Not con Is Nothing Then Set objExcel = CreateObject("Excel.Application") Set exWb = objExcel.Workbooks.Open("C:\Users\adong\Desktop\Reporting.xlsx") con.Caption = exWb.Sheets("Summary").Cell(5, 4).Value exWb.Close False Set exWb = Nothing objExcel.Quit End If End Sub Function ActiveXControlByName(doc As Document, theName As String) As Object Dim ilsh As InlineShape Dim sh As Shape, ob As Object For Each ilsh In doc.InlineShapes If ilsh.Type = wdInlineShapeOLEControlObject Then Set ob = ilsh.OLEFormat.Object If ob.Name = theName Then Set ActiveXControlByName = ob Exit Function End If End If Next ilsh For Each sh In ActiveDocument.Shapes If sh.Type = msoOLEControlObject Then Set ob = sh.OLEFormat.Object If ob.Name = theName Then Set ActiveXControlByName = ob Exit Function End If End If Next sh 'if got here then control was not found... Set ActiveXControlByName = Nothing End Function