Quite simply they allow you to create objects, you are in all likelihood already using class modules without realising it - Sheets, Userforms, This_Workbook are all examples of Class Modules.
The primary reason that they're used in VBA is to listen for events, to put this into context, what are commonly thought of as "Events" in VBA :
Etc, are not events. What's happening is that The sheet, or userform object is raising an event that the object that is created by the Sheet Class or Userform Class is listening for. AS it's listening (or subscribing to), it can run a sub when it happens - Hence the above code just being normal subs.
So why is this useful? Or more specifically, why would you want to create your own?
More often than not in VBA, for extending controls. Consider wanting to have a textbox only accept numeric input, one way would be to have something like this:
Which is fine, but it's usually neater to do all your setting up at the beginning of a userform, so we could write a class like this:
We can then loop through all the textboxes in the userform and make them numeric only - in this case by looking at how they're named:
This means that there's no need to add the additional OnlyNumbers call in each Change Sub and keeps the userform clean of code that doesn't relate to its function. It also allows us to dynamically add more textboxes at run time and make them numeric only - this isn't something that's done without classes.
There are other reasons to use classes too, but they relate to the way you structure your code, breaking it into logical chunks that makes for easier testing and refactoring - though one technically doesn't need to use classes for those, it makes things easier.
Bookmarks