用户定义types未定义 – 从Excel控制Word

我试图做一些相对简单的复制和从Excel 2007粘贴到Word 2007中。我浏览过这个网站和其他人,并不断挂上同样的事情 – 第三行下面的代码不断给我的“用户types备注定义“错误消息。 我真的很困惑,因为我只是从另一个解决scheme中解除了这个问题(并且与我试图解除的其他解决scheme有类似的问题)。 有人可以请教我什么是造成错误,为什么?

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 

提姆·威廉姆斯在评论中提到了这个答案。

为了解决此问题,您必须将Word对象库引用添加到您的项目。

Visual Basic Editor ,selectTools然后selectReferences ,向下滚动列表直到看到Microsoft Word 12.0 Object Library 。 选中该框并点击Ok

从那一刻起,当您键入Word.时,您应该已启用自动完成functionWord. 确认参考是否正确设定。

根据在Excel VBA中使用New关键字和调用CreateObject有什么区别? ,要么

  • 使用一个无types的variables:

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

要么

  • 通过Tools->References...将对Microsoft Word <version> Object Library的引用添加到VBA项目中,然后创build一个typesvariables并使用VBA New运算符初始化它:

     Dim appWD as New Word.Application 

    要么

     Dim appWD as Word.Application <...> Set appWd = New Word.Application 
    • 这里CreateObject相当于New ,它只引入代码冗余

一个typesvariables会给你自动完成。