At some point, you’ll need to retrieve a reference to a new instance of your class. If you want to add a new item to your data structure, you’ll need a pointer to that new item so you can get back to it later. Of course, Basic (after all, as many folks will argue, this is still just Basic) has never supported real pointers, and dynamic data structures require pointers, right? Not quite, luckily!
VBA allows you to instantiate a new element of a class and retrieve a reference to it:
Dim objVar As New className
or
Dim objVar as className
‘ Possibly some other code in here.
Set objVar = New className
You choose one of the two methods for instantiating a new item based on your needs. In either case, you end up with a variable that refers to a new instance of the class.
Be wary of using the New keyword in the Dim statement. Although this makes your code shorter, it also can cause trouble. This usage allows VBA to instantiate the new object whenever it needs to (normally, the first time you attempt to set or retrieve a property of the object) and therefore runs the new object’s Initialize event at that time. If you want control over exactly when the new object comes into being (and when its Initialize event procedure runs), use the New keyword with the Set statement. This will instantiate the object when you’re ready to, not at some time when you might not be expecting it.
After this statement, objVar contains a pointer to the new member of the className class. Even though you can’t manipulate, view, or otherwise work with pointer values as you can in C/C++, the Set/New combination at least gives VBA programmers almost the same functionality that Pascal programmers have always had, although the mechanism is a bit clumsier: you can create pointers only to classes in VBA, although Pascal allows pointers to almost any datatype.