您可以将类添加到类属性VBA

时间:2017-02-04 16:09:48

标签: excel-vba class object class-properties vba

所以我有两个Class模块,ClassA和ClassB,以及一个模块中的sub,我尝试将Class B中的对象添加到ClassA中对象的属性中。

According to the VBE Glossary,类是对象,属性集语句可以添加对象类型,所以看起来这应该是可能的。但是,当我运行测试子时,我得到一个"对象变量或者没有设置块变量"错误

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

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 个答案:

答案 0 :(得分:0)

以下是我进行必要更改后的代码,以便能够将类对象添加到我的属性中。除了建议更改pinkfloydx33之外,我还添加了" Set"意图保存对象的属性的语句的关键字,以及所述属性的更改数据类型到要保存的类的名称。

'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