VBA Static Class "WithEvents"?

Viewed 109

Disclaimer - I am by no means a VBA expert; I am a hack.

However, I've got some class modules that are static (using Attribute VB_PredeclaredId = True )

I'd like to define some custom events with them, too (Public Event Foo(ByVal Bar As Boolean); however, since I am not instantiating the class, I'm not finding any info on any "Attributes" that will include "WithEvents" when "PreDeclaredID" is true.

Yes, I can use the class without its being static; however, I'd prefer to find a way for it to be declared automatically WithEvents, if it's possible.

1 Answers

The class has static semantics, but it's not static in the static sense you're referring to.

The VB_PredeclaredId attribute set to True means the compiler generates a global (or project-scoped, if the class is private) instance that is named after the class module itself.

In other words, there is literally an object/instance named Class1 (assuming the class module is named Class1), exposing the default interface defined by the Class1 module (i.e. it's an object whose compile-time type is Class1 regardless of what other interfaces that class might be implementing).

So you are not instantiating it, but the VBA compiler does.

And that object behaves every single bit the same as any other object you might have - there is no reason a Public Event could not be declared in it, and you can Set a WithEvents object variable to that "free" global instance, which you can refer to by name from anywhere in the project:

Private WithEvents Thing As Class1 '<~ requires Public Event declaration in Class1.

Private Sub Class_Initialize()
    Set Thing = Class1 '<~ will not compile unless Class1 has VB_PredeclaredId=True.
End Sub
Related