首页 > 解决方案 > VBA - 嵌套类

问题描述

[编辑代码]对不起新手问题。我试图在 VBA for Excel 中测试嵌套类,但收到错误消息。谁能帮我理解为什么?谢谢!

课内:

' CLASS MODULE - cInside
' Member variables
Private m_Value As Integer

' Properties
Property Get Value() As Integer
    Value = m_Value
End Property

Property Let Value(i As Integer)
    m_Value = i
End Property

' Methods
Sub init()
    m_Value = 0
End Sub

Sub Inc()
    m_Value = m_Value + 1
End Sub

课外:

' CLASS MODULE - cOutside
' Member variables
Private m_Num1 As New cInside
Private m_Num2 As New cInside

' Properties
Property Get Num1() As cInside
    Num1 = m_Num1.Value
End Property

Property Get Num2() As cInside
    Num2 = m_Num2.Value
End Property

Property Set Num1(i As cInside)
    Set m_Num1 = i
End Property

Property Set Num2(i As cInside)
    Set m_Num2 = i
End Property

主程序:

Sub Main()

Dim o As New cOutside
Dim i As New cInside

i.Value = 9
i.Inc
Debug.Print i.Value '<-- this works

Set o.Num1 = i
o.Num1.Inc  '<-- object variable or with block variable not set
Debug.Print (o.Num1.Value)

End Sub

再次感谢你!

标签: ms-accessvba

解决方案


n.Num1返回 an Integer,它不是 的实例cInside,因此没有Inc成员,这使其成为编译器抱怨的无效限定符;-)

您的cOutside班级需要以某种方式公开它:

Property Get ComposedObject1() As cInside
    Set ComposedObject1 = m_Num1
End Property

然后调用代码可以这样做:

n.ComposedObject1.Inc

我称其为“组合”,因为您所做的不是“嵌套”,而是“组合”。VBA 不支持嵌套类,它是在另一个类模块中定义的类模块,如下所示:

Class Outside
    '... members...

    Class Inside
        '...members...
    End Class
End Class

VB.NET 可以做到这一点,但在 VBA 1 类模块中只能定义 1 个类。


推荐阅读