Word报告自动化从Excel中获取数字

时间:2017-04-06 05:57:25

标签: excel word-vba

我需要通过从Excel中提取数字来自动化单词报告。我搜索并关注了来自http://www.makeuseof.com/tag/integrate-excel-data-word-document/

的代码

代码无法正常运行并遇到许多错误。 1. Excel无法打开 2.遇到运行时错误'438':对象不支持此属性或方法。

我使用了网站建议的“早期绑定”代码并且不起作用并且研究使用“后期绑定”。仍然无法正常工作。我插入“Microsoft Excel 14.0对象库”并在“ActiveX控件”

下的word doc中插入“Label”

不知道出了什么问题。

当前的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

1 个答案:

答案 0 :(得分:0)

Adapting code from: https://www.experts-exchange.com/questions/26874253/How-to-loop-with-VBA-on-all-controls-placed-in-a-Word-doc.html

You can write a utility function to get an ActiveX control given its name and the hosting document:

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