2012-07-30 244 views
2

我正在嘗試做一些相對簡單的複製並從Excel 2007粘貼到Word 2007中。我瀏覽過本網站和其他人,並且一直在關注同一事物 - 以下代碼的第三行不斷給我提供「用戶類型備註定義」錯誤消息。我很困惑,因爲我剛剛從另一個解決方案中解脫出來(並且與我試圖解除的其他解決方案有類似的問題)。有人可以請教我什麼導致錯誤,爲什麼?用戶自定義類型未定義 - 控制Excel中的Word

Sub ControlWord() 
' **** The line below gives me the error **** 
Dim appWD As Word.Application 
' Create a new instance of Word & make it visible 
Set appWD = CreateObject("Word.Application.12") 
appWD.Visible = True 

'Find the last row with data in the spreadsheet 
FinalRow = Range("A9999").End(xlUp).Row 
For i = 1 To FinalRow 
    ' Copy the current row 
    Worksheets("Sheet1").Rows(i).Copy 
    ' Tell Word to create a new document 
    appWD.Documents.Add 
    ' Tell Word to paste the contents of the clipboard into the new document 
    appWD.Selection.Paste 
    ' Save the new document with a sequential file name 
    appWD.ActiveDocument.SaveAs Filename:="File" & i 
    ' Close this new word document 
    appWD.ActiveDocument.Close 
Next i 
' Close the Word application 
appWD.Quit 
End Sub 
+7

您需要在項目中設置對Word庫的引用(您可以在VB編輯器下的Tools >> References下執行此操作) – 2012-07-30 20:18:53

+0

感謝Tim-從未這麼做過。 – 2012-07-30 20:32:05

+0

完美工作,謝謝! – 2012-07-30 20:33:32

回答

7

對此答案予以Tim Williams在評論中提及。

爲了解決此問題,您必須將Word對象庫引用添加到您的項目中。

Visual Basic Editor內部,選擇Tools然後References並向下滾動列表直到看到Microsoft Word 12.0 Object Library。選中該框並點擊Ok

從那一刻起,當您鍵入Word.以確認參考設置正確時,您應該已啓用自動完成功能。

0

作爲每What are the differences between using the New keyword and calling CreateObject in Excel VBA?,無論是

  • 使用一個無類型變量:

    Dim appWD as Object 
    appWD = CreateObject("Word.Application") 
    

  • Microsoft Word <version> Object Library添加引用進入VBA項目經由Tools->References...,然後創建一個類型的變量並初始化它with the VBA New operator

    Dim appWD as New Word.Application 
    

    Dim appWD as Word.Application 
    <...> 
    Set appWd = New Word.Application 
    
    • CreateObject相當於New這裏,只介紹了碼的冗餘

一個類型變量會給你自動完成。

相關問題