Event handling for dynamically created controls on Word Document

Event handling for dynamically created controls on Word Document

We are making a macro-enable word document with various ActiveX controls, FormField controls (such as combo box, buttons, and textfield ) etc.
Many of these controls are added dynamically that is when the user clicks a button or when rows in a table are added during runtime.

Now we need to attach events to these controls created at runtime. Please guide us as to how this can be done.


ActiveX controls expose their API in the ThisDocument module. If you select the ThisDocument entry for a document, then look at the list in the Properties window you should see the controls listed. You'll also see them in the list at the top left of the Code window. Select a control from the list, and you'll get a list of its events in the dropdown at the top, right.

 You'd need to ensure that you have programmatic access to the VBA Editor. Installation default is that this isn't allowed, as it's a definite security risk. It would need to be enabled through the Trust Center or through a Group Policy.

It's possible to dynamically alter the content of any code component using the Visual Basic Extensibility library. You'd want to add a reference to that in your project. This library is not very well documented and there aren't a lot of code examples out there. Some, but not a lot, and I can't recall any discussion, ever, on this particular topic...

Essentially, you'd need the name of the control. With that, you can build procedures for the events (strings and/or text files). These can be loaded into the CodeModule of a VBComponent, in this case Document.VBProject.VBComponents("ThisDocument").

The object Document.VBProject.VBComponents("ThisDocument").CodeModule provides a number of useful properties and methods, such as AddFromString and AddFrom File. Once you have a reference to the library, typing a "." will give you Intellisense.

Copyright © 2007-2012 www.chuibin.com Chuibin Copyright