用户定义的类型未定义-从Excel控制Word

11

我试图将一些相对简单的内容从Excel 2007复制粘贴到Word 2007中。我查看了这个网站和其他网站,但总是被同一个问题困扰 - 下面代码的第三行不停地报“未定义用户类型”错误信息。我很困惑,因为我只是从另一个解决方案中抄来的(并且在尝试抄取其他解决方案时也遇到类似的问题)。有人能告诉我是什么原因导致了这个错误,以及为什么会出现吗?

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中完成)。请注意保持原文意思不变,并尽可能地使翻译通俗易懂。 - Tim Williams
感谢Tim-以前从未做过这样的事情。 - Tommy Z
可能是重复的问题:'User Defined Type Not Defined' error - Zev Spitz
2个回答

15

这个答案在Tim Williams的评论中提到。

为了解决这个问题,您需要将Word对象库引用添加到您的项目中。

Visual Basic Editor中,选择工具,然后选择引用,滚动列表直到看到Microsoft Word 12.0 Object Library。选中该框并点击确定

从那时起,当您键入Word.时,您应该已经启用了自动完成,以确认参考已正确设置。


1
这就是修复方法!我们现在已经升级到 Microsoft Word 16.0 Object Library。 - Allen J
1
谢谢!非常棒的解决方案。 - Michthan

4
根据Excel VBA中使用New关键字和调用CreateObject有什么区别?,两者均可创建新对象。
  • use an untyped variable:

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

或者

  • Add a reference to Microsoft Word <version> Object Library into the VBA project via Tools->References..., then create a typed variable and initialize it with the VBA New operator:

    Dim appWD as New Word.Application
    

    or

    Dim appWD as Word.Application
    <...>
    Set appWd = New Word.Application
    
    • CreateObject is equivalent to New here, it only introduces code redundancy

使用类型化的变量将会让自动补全更加便捷。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接