I am writing a program in Excel VBA that will basically start with one textbox and one command button, and the command button will create a new textbox and command button underneath it, and that command button will in turn create a new textbox and command button, and so on. Hope you followed that mess.
I can create the initial button no problem (it has to be dynamically created so it has the opportunity to be deleted later). My problem is then with creating the click()
event handler. I need all the click()
events to do the same thing, but name the new Objects relative to its own name. This is all blowing my mind, I would really appreciate a little help.
Feel free to ask for specific information, but I haven't really been able to wrap my head around the topic well enough to write some test code yet.
Create a custom class module called CEventClass (Insert - Class Module, F4 to change the name). Type this code into the class module
Now create a Userform with no controls on it. Put this code in the form's code module
Now when you run the form, those two events will fire if you click/change the control.
You may note that there is no AfterUpdate event for the textbox. That event is not actually a textbox event, but an event of the control container for the textbox, so you can't expose it this way. That's one reason I prefer to create all the controls at design time and hide or unhide them as needed. I still might use WithEvents for some controls just so I don't have to repeat code so much. But for things like TextBox_AfterUpdate, I just create all the event procedures at design time.
Update:
If you want the event to create new buttons, you have to do a couple more things. First, you have to expose the collection outside of the userform. You add this to your Userform module
Then you change your commandbutton event code to create a new button
This creates a new button 40 points below whichever was clicked. You don't say what your logic is for naming or positioning, so I assume you can work that out. Use cmdEvent.Parent to get a reference to the Userform.