Class (Static) Methods in VBA

1. Create a normal class containing the public method(s) you need to be ‘static’

2. Include a public method [in this ‘static’ class] that initialises the [private] ‘static fields’ within the class (it can take parameters if you wish)

3. Create a module acts as a factory

Public Function CreateStaticClass(parameters for 'constructor') As StaticClass

    Dim static As StaticClass
    Set static = New StaticClass
    Call StaticClass.Constructor(pass in parameters)
    Set CreateStaticClass = static

End Function

4. you can now use the ‘static’ class by calling CreateStaticClass(‘parameters’).MethodName(‘parameters’)
there is no need to initialise the instance as that is done by the factory method

5. (Optional) If you want to enforce singleton instances you can create a module that acts as a singleton container – include a private instance variable and a public accessor property. optionally you can use a ‘let’ setter to allow the singleton to be ‘replaced’ with a new [static] class (using different constructor parameters – see #2,3). Use ‘Let’ for the setter, so you can assign the singleton without using ‘set’ ala OO languages

Private curStaticClass as StaticClass

Public Property Get CurrentStaticClass() As StaticClass 

    If curStaticClass Is Nothing Then Set curStaticClass = CreateStaticClass

    Set CurrentStaticClass = curStaticClass  

End Property

Public Property Let CurrentStaticClass(value As StaticClass)

    If Not (curStaticClass Is Nothing) Then Set curStaticClass = Nothing

    Set curStaticClass = value 

End Property

6. To assign the singleton:

CurrentStaticClass = CreateStaticClass(parameters)

7. To use the singleton:

[value = ] CurrentStaticClass.MethodName(parameters)

Leave a Comment