Adding a button and Click event at run-time

Many developers recognize the need to disable certain controls in their application to either keep from confusing users as to which button to click or to keep users from clicking buttons at an inappropriate time. Usually this is done by programmatically enabling/disabling the button. However there is another way. At run-time, you can create a button or subroutine that does its own thing and then, before it is finished, creates another button and adds an event procedure to the button just created.

The following steps help you create a Word 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, you can apply the same concepts to programmatically manipulate controls in Microsoft Excel workbooks.

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".

4. Insert a new module and add the following code:

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 ends up residing in the ThisDocument 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

5. Run the macro "Test".

6. 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.

Note: If you receive the following error:

"Programmatic Access to Visual Basic Project is not trusted."

Office XP and Office 2003 add a security option to deliberately lock out programmatic access to the VBA object model from any Automation client unless a user chooses to permit such access. This is a per user and per application setting, and denies access by default. To turn on the access, do the following:

1. Open the Office application in question. On the Tools menu, click
   Macro, and then click Security to open the Macro Security dialog box.

2. On the Trusted Sources tab, click to select the Trust access to
Visual Basic Project
check box to turn on access.

3. Click OK to apply the setting. You may need to restart the
   application for the code to run properly if you automate from a
   Component Object Model (COM) add-in or template.