如何向 Word 文档添加按钮并在运行时分配其 Click 事件

摘要

本文演示如何使用 Microsoft Visual Basic for Applications宏以编程方式将控件添加到 Microsoft Word 文档,并为该控件添加 Click 事件处理程序。

更多信息

以下步骤演示了如何创建 Word 宏,该宏将控件添加到文档,并在运行时分配该控件的 Click 事件。 步骤适用于 Word。 但是,可以应用相同的概念以编程方式操作 Microsoft Excel 工作簿中的控件。

注意

能够在运行时操作 Microsoft Office 文档的 Visual Basic 项目需要对 Microsoft Visual Basic for Applications 扩展库的引用。

创建示例的步骤

  1. 在 Word 中启动新文档。

  2. 按 Alt+F11 转到 Visual Basic 编辑器。

  3. “工具”菜单上,单击“引用”

  4. 选择 Microsoft Visual Basic for Applications扩展性的引用。

  5. 插入新模块,然后添加以下代码示例。

    Sub Test()
    
    'Add a command button to a new document
    Dim doc As Word.Document
    Dim shp As Word.InlineShape
    Set doc = Documents.Add
    
    Set shp = doc.Content.InlineShapes.AddOLEControl(ClassType:="Forms.CommandButton.1")
    shp.OLEFormat.Object.Caption = "Click Here"
    
    'Add a procedure for the click event of the inlineshape
    '**Note: The click event resides in the This Document module
    Dim sCode As String
    sCode = "Private Sub " & shp.OLEFormat.Object.Name & "_Click()" & vbCrLf & _
            "   MsgBox ""You Clicked the CommandButton""" & vbCrLf & _
            "End Sub"
    doc.VBProject.VBComponents("ThisDocument").CodeModule.AddFromString sCode
    
    End Sub
    
  6. 运行宏“Test”。

  7. 宏“测试”完成运行后,你将在新文档上看到新的 CommandButton 控件。 单击 CommandButton 控件时,将触发控件的 Click 事件。

Word 2002 和 Word 2003 的其他说明

默认情况下,将禁用对 Word VBA 项目的访问。 禁用时,上述代码可能会生成运行时错误“6068”,“不信任对 Visual Basic 项目的编程访问”。有关此错误以及如何更正此错误的详细信息,请单击以下文章编号以查看 Microsoft 知识库中的文章:

282830 对 Office VBA 项目的编程访问被拒绝