2017-04-06 23 views
1

我需要通過從Excel中提取數字來自動報告單詞。我搜索並遵循源代碼http://www.makeuseof.com/tag/integrate-excel-data-word-document/Word報告自動化從Excel中採集數字

代碼無法正常運行並遇到大量錯誤。 1. Excel未打開 2.遇到運行時錯誤'438':對象不支持此屬性或方法。

我已經使用了網站建議的「早期綁定」代碼,不工作,研究使用「後期綁定」。仍然不起作用。我插入「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 
+0

除非在創建Excel實例後添加'objExcel.Visisble = True',否則不會看到Excel打開。你在哪一行發生錯誤? –

+0

謝謝蒂姆。你現在可以掌握我的技能水平。 – Andy

+0

這是它顯示的運行時錯誤 – Andy

回答

0

適應代碼:https://www.experts-exchange.com/questions/26874253/How-to-loop-with-VBA-on-all-controls-placed-in-a-Word-doc.html

您可以編寫一個效用函數來得到一個ActiveX控件,它的名字和託管文件:

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