Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to overload the constructor / initialize procedure for a class in VBA?

In C#, I know that I can overload the constructor for a class by specifying it in the body of the class:

public class MyClass()
{
    public MyClass(String s) { ... }
}

This overrides the default constructor (which has no parameters) and forces the class to be initialized with parameter s.

I know that in VBA I can initialize my class with Private Sub Class_Initialize(), but I don't know if there's a way to force my class to be initialized with parameters. Can this be done?

like image 822
Ben McCormack Avatar asked Nov 13 '09 18:11

Ben McCormack


People also ask

How to initialize class in VBA?

The Initialize event occurs when you: Create a new instance of a class directly by using the New keyword with the Set statement. Dimension an object variable using the New keyword and creating an instance of a class indirectly by setting or returning a property or applying a method defined in the class module.

Can we initialize constructor?

A class object with a constructor must be explicitly initialized or have a default constructor. Except for aggregate initialization, explicit initialization using a constructor is the only way to initialize non-static constant and reference class members.

How do you initialize a constructor?

Constructors for Initialization. A constructor must have the same name as the class. A constructor's function definition cannot return a value. No type, not even void, can be given at the start of the constructor's function prototype or in the function header.


3 Answers

As Jtolle indicated, this is simply not possible in VBA/VB6. There is no perfect way to work around this but, what I personally do is create a Public/Friend sub call Initialize with the parameters I want (in VBA/VB6 you use "Optional" parameters for overloading) and then put a quick check in all exposed members of the class that throws an exception if you try to access them without running the initialize method. A basic example might look like this:

Option Explicit

Private m_blnInitialized As Boolean
Private m_lngID As Long
Private m_strFirstName As String

Public Sub Initialize(ByVal ID As Long, Optional ByVal someOtherThing As String = vbNullString)
    If m_blnInitialized Then Me.Clear
    m_lngID = ID
    m_strFirstName = SomeLookUp()
    If LenB(someOtherThing) Then
        ''Do something here.
    End If
    m_blnInitialized = True
End Sub

Public Property Get ID() As Long
    If Not m_blnInitialized Then Err.Raise eStandardErrors.eNotInitialized
    ID = m_lngID
End Property

Public Property Get FirstName() As String
    If Not m_blnInitialized Then Err.Raise eStandardErrors.eNotInitialized
    FirstName = m_strFirstName
End Property

Private Function SomeLookUp() As String
    ''perform magic on Me.ID
End Function

Public Sub LoadPicture()
    If Not m_blnInitialized Then Err.Raise eStandardErrors.eNotInitialized
    ''More magic
End Sub

Public Sub Clear()
    If Not m_blnInitialized Then Err.Raise eStandardErrors.eNotInitialized
    m_strFirstName = vbNullString
    m_lngID = 0&
    m_blnInitialized = False
End Sub

It's not great, but it's about as good as it's going to get with VBA/VB6.

like image 136
Oorang Avatar answered Sep 21 '22 02:09

Oorang


You already have two correct answers; you can't literally have a constructor with parameters in VBA.

Oorang's workaround is basically right - have a separate "init" method. When I do take an object-oriented approach to something in Excel/VBA, I prefer to hide both object creation and init in a regular function. So I'd have mkFoo(parm) and call it to get a Foo instance. mkFoo() would create a New Foo instance and call Foo.init(). If you only ever create instances that way, you don't need to check if your instance has been initialized over and over again.

If you're really trying to be correct and not supply an object with a maybe-now-dangerous init() method exposed, you can have an IFoo interface (with no init method) that is implemented by Foo. Then mkFoo() returns an IFoo, and any users of the actual Foo never see the init() method at all.

Of course, now you have a bunch of modules just for Foo - one for IFoo, one for each actual Foo class, and one for your "Foo factory" function...thus my comment that this is one of many reasons why OOP in VBA is a PITA, even if it is useful sometimes.

EDIT: This was an edit by onedaywhen from shortly after the original answer, but I pulled it out separately just now since it is really a separate thought:

Speaking of Excel, you could relocate the Foo class into a .xla add-in and make the class PublicNotCreateable. The Public Function mkFoo(parm) could reside in a standard .bas module in the add-in and therefore called a bit like a static class in C#. This forces client code to use mkFoo as the only way of creating a Foo instance. No doubt there is a MS Access analogy to Excel's .xla add-ins.

like image 25
jtolle Avatar answered Sep 24 '22 02:09

jtolle


No, classes cannot be initialized with parameters in VBA. This wouldn't be legal because of the Dim ... As New ... statement, which implicitly constructs objects when they're first accessed.

Dim x As New MyClass

x.Prop = 42 ' Before x.Prop is set, x is implicitly constructed
like image 30
Tmdean Avatar answered Sep 24 '22 02:09

Tmdean