Access JumpStart 2.0 | Blog

A Rapid Development Framework for Microsoft Access

In other languages, when you build a class, there are things called constructors which can take parameters when you instantiate the class as an object in order to initiate it. This is very handy, as you can abbreviate what you need to do into a much smaller number of lines.

In VBA, there are no constructors you can use when you create an instance of the objects using the New keyword. There is a Class_Initialize event that occurs when a new instance is created, but it does not accept any parameters.

A common example for any kind of class wrapping another object like a form or report is to pass a parameter to the wrapper of the instance that you are wrapping.

One way is to create a custom initialization method in the class. Say we call it Setup, and we will give it parameters.

So how do we initialize a class to set it up using some parameters?

Dim EnhancedForm As MyFormWrapper
Set EnhancedForm = New MyFormWrapper
EnhancedForm.Setup Me

Another way is to use the factory pattern which utilizes a function to create a new instance, configure it, and return the reference to it.

That would look something like this for the above example:

    Dim EnhancedForm As MyFormWrapper
    Set EnhancedForm = GetNewMyFormWrapper(Me)
    
    Public Function GetNewMyFormWrapper(frm As Access.Form) As MyFormWrapper
      Dim ef As MyFormWrapper
      Set ef = New MyFormWrapper
      ef.Setup Me
      Set GetNewMyFormWrapper = ef
    End Function

    This could end up being more convenient as it only uses two lines to setup an explicit instance instead of 3. If you are going to be doing this a lot on multiple forms, this might end up saving some lines of code future you or a new maintainer will have to read.