Can You Add a Class to a Class Property VBA

1.5k Views Asked by At

So I have two Class modules, ClassA and ClassB, and a sub in a module in which I try to add an object from Class B to a property of an object in ClassA.

According to the VBE Glossary, classes are objects and the property set statement can add object types, so it seems like this should be possible. However, when I run the test sub I get an "object variable or with block variable not set" error

The Sub:

Sub test()

Dim Class_A_Object As ClassA
Dim Class_B_Object As ClassB

Set Class_A_Object = New ClassA
Set Class_B_Object = New ClassB

Class_B_Object.Class_B_Property = 42
Class_A_Object.Class_A_Property = Class_B_Object

End Sub

ClassA:

Private a_Class_A_Property As Object

Public Property Set Class_A_Property(pClass_A_Property As Object)
    a_ClassA_Property = pClass_A_Property
End Property

Public Property Get Class_A_Property() As Object
    Class_A_Property = a_Class_A_Property
End Property

Class B:

Private b_Class_B_Property As Integer

Public Property Let Class_B_Property(pClass_B_Property As Integer)
    b_Class_B_Property = pClass_B_Property
End Property

Public Property Get Class_B_Property() As Integer
    Class_B_Property = b_Class_B_Property
End Property
1

There are 1 best solutions below

0
On

Here is the code after I made changes necessary for it to be able to add a class object to my property. As well as making the change pinkfloydx33 suggested, I added the "Set" keyword to the statements of the properties intending to hold the objects and changed data type of said properties to the name of the class to be held.

'The Sub:
Sub test()

Dim Class_A_Object As ClassA
Dim Class_B_Object As ClassB

Set Class_A_Object = New ClassA
Set Class_B_Object = New ClassB

Class_B_Object.Class_B_Property = 42
Set Class_A_Object.Class_A_Property = Class_B_Object

End Sub

'ClassA:
Private a_Class_A_Property As Class B

Public Property Set Class_A_Property(pClass_A_Property As ClassB)
    Set a_ClassA_Property = pClass_A_Property
End Property

Public Property Get Class_A_Property() As ClassB
    Set Class_A_Property = a_Class_A_Property
End Property

'Class B:
Private b_Class_B_Property As Integer

Public Property Let Class_B_Property(pClass_B_Property As Integer)
    b_Class_B_Property = pClass_B_Property
End Property

Public Property Get Class_B_Property() As Integer
    Class_B_Property = b_Class_B_Property
End Property