VBA - Nested Class

Helloguys Source

[Edited the code] Sorry for newbie question. I was trying to test nested classes in VBA for Excel but got error message. Can anyone help me understand why? Thank you!

Inside class:

' 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

Outside class:

' 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

Main program:

Sub Main()

Dim o As New cOutside
Dim i As New cInside

i.Value = 9
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

Thank you again!



answered 7 days ago Mathieu Guindon #1

n.Num1 returns an Integer, which isn't an instance of cInside, and therefore doesn't have an Inc member, which makes it an invalid qualifier for the compiler to complain about ;-)

Your cOutside class needs to expose it somehow:

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

Then the calling code could do this:


I called that "composed", because what you're doing isn't "nesting", but "composition". VBA doesn't supported nested classes, which would be a class module defined inside another class module, like so:

Class Outside
    '... members...

    Class Inside
    End Class
End Class

VB.NET can do that, but in VBA 1 class module can only define 1 class.

comments powered by Disqus