I decided to make this an answer because I am doing something similar and I confirmed that it works.
You can store the OLEobjects
in a Collection
, of arbitrary size, containing Custom Class
Objects that include the OLEobjects and associations and the events that you need. Thus you can completely avoid any code stubs.
- Create a
Custom Class
to bind the Button and TextBox pairs.
- Declare the Button object
WithEvents
.
- Include your call-back in the exposed button event handler in the Class Module.
- Put a
Public
routine in a Standard Module
to initialise a Collection
of these Custom Class
objects by spanning the Form Controls. You can also use this to Add
the controls programmatically as a 'reBuild' option. The Collection can be inside another Class Module with all of the management routines, but it needs to be Instantiated and loaded in a Standard Module
.
- Put a public routine in a standard module to receive the call-backs with whatever context you need. This can also be in a Worksheet Module if it makes for better encapsulation. You can use late binding to reference the callback or CallByName.
You need to bear in mind that the Module of the Form will recompile every time you add a control, so you have to be careful where you put your code.
My application has the controls directly on the Worksheet Surface, so I can't put the the Collection Class in, or source any initialisation of the Collection from the Worksheet module. This would amount to self modifying code and it grinds excel to a halt.
I dreamed this idea up through bloody-minded idealism (not necessarily a good thing) but, of course, I was not the first one to think of it as you can see here. @Tim Williams explains it in his answer. You can also google VBA Control Array Events to see plenty of similar examples including an excellent article by @SiddharthRout. In line with the VB6 analogy, he uses an Array
instead of a Collection
to achieve the same result.
I'll try to post some code later. My application is a bit different so it will take a lot of work to trim it down, but the principle is the same.
The other thing to bear in mind is that VBE really struggles with this type of thing so don't worry if it is loading up you processors. After you re-start with VBE off, all will be fine.