So lets create our template for the object that will listen for the button clicks, just like in the userform example above, we use WithEvents to let our object know what to listen out for:
Class2
Then in our UserForm:
Pretty nifty, but it also allows us to extend the button, we can add more functionality to it, suppose we wanted an option to make the button red - we can just add it to our class:
Then we can change our original code to:
This is really useful for creating custom versions of controls that are re-usable and don't require you to clutter up your userform code. Now of course it would be perfectly possible to make the button red by creating a custom sub in a module, however that approach, I would argue, starts to spread your code around and makes it more difficult to follow - using a class means that all the custom methods for our custom control are held in a single logical place and encapsulated. You don't even need to be adding dynamically for this useful functionality either, if we wanted to add the makeRed functionality to an existing button we could simply do:
So again, whilst we could have created a function to make the button red and put it in a module, this method actually makes the code easier to come back to (you immediately know that the makeRed method is in Class2) and logically groups the custom button functionality together. You can take this even further, by creating a whole hierarchy of custom controls, have a look at a custom properties box I made here: http://www.excelforum.com/tips-and-t...ddly-bits.html.
I can create a class with a specific purpose and just expose public methods, all the faffing is done in the internals and I don't have to worry about it when consuming the object in normal code, this makes the parent code much easier to read and more fluid. It also allows much easier re factoring - all I have to keep the same are the method names and return types - since any application using the object doesn't know/care about the internals. It also allows proper testing, my moving application logic away from the user interface controls and into its own model you can write automated test scripts, for an idea about what I'm talking about here take a look at MVC or more relevantly MVVM design patterns.
Phew, that went on a bit longer than intended; hope some of it is useful anyway
Bookmarks