HOWTO: Add a Button to a Word Document and Assign Its Click Event at Run-time

ID: Q246299


The information in this article applies to:
  • Microsoft Word 2000


SUMMARY

This article demonstrates how you can use a Visual Basic for Applications macro to programmatically add a control to a Microsoft Word document and add a Click event handler for that control.


MORE INFORMATION

The following steps illustrate how you can create a Word 2000 macro that will add a control to a document and assign that control's Click event at run-time. Although the steps below are for Word 2000, you can apply the same concepts to programmatically manipulate controls in Microsoft Excel workbooks.

NOTE: The ability to manipulate the Visual Basic Project of an Office document at run-time requires a reference to the Microsoft Visual Basic for Applications Extensibility library.

Steps to Create Sample

  1. Start a new document in Word.


  2. Press Alt+F11 to go to the Visual Basic Editor.


  3. Click Tools and then References and select the reference for "Microsoft Visual Basic for Applications Extensibility". If you do not see it in the list, the required file is Vbeext1.olb and it is usually located at:


  4. 
    C:\Program Files\Common Files\Microsoft Shared\Vba\Vbeext1.olb 
  5. Insert a new module and add the following code:


  6. 
    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 
  7. Run the macro "Test".


  8. Once the macro "Test" finishes running, you will see a new CommandButton control on a new document. When you click the CommandButton, it's Click Event fires.


Additional query words: kbmacro vba runtime

Keywords : KbVBA kbWord kbGrpDSO kbDSupport kbword2000
Version : WINDOWS:2000
Platform : WINDOWS
Issue type : kbhowto


Last Reviewed: January 12, 2000
© 2000 Microsoft Corporation. All rights reserved. Terms of Use.