【问题标题】:User defined type not defined- controlling Word from Excel用户定义类型未定义 - 从 Excel 控制 Word
【发布时间】:2012-07-28 13:23:13
【问题描述】:

我正在尝试从 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

【问题讨论】:

  • 您需要在项目中设置对 Word 库的引用(您可以在 VB 编辑器中的 Tools>>References 下进行)
  • 感谢蒂姆-以前从未这样做过。

标签: vba excel ms-word excel-2007


【解决方案1】:

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

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

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

从那时起,当您键入 Word. 以确认引用设置正确时,您应该启用自动完成功能。

【讨论】:

  • 这是修复!我们现在可以使用 Microsoft Word 16.0 对象库。
  • 谢谢!很好的解决方案
【解决方案2】:

根据What are the differences between using the New keyword and calling CreateObject in Excel VBA?,要么

  • 使用无类型变量:

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

  • 通过Tools->References...Microsoft Word <version> Object Library的引用添加到VBA项目中,然后创建类型化变量并初始化with the VBA New operator

    Dim appWD as New Word.Application
    

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

类型化变量将为您提供自动完成功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-30
    • 2014-08-07
    • 2013-01-22
    • 2011-04-08
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多