excelvbaexcel-365

How to implement a Default property usage in nested class hierarchy inside VBA?


Consider the following code

parent.cls

Public Child as New ChildClass

ChildClass.cls

Private m_internal As New Collection

Public Property Get Item(index As Integer) As Variant
    Attribute Item.VB_UserMemId = 0          <-- used to mark the default property
    If IsObject(m_internal(Item)) = True Then
        Set Item = m_internal(index)
    Else
        Item = m_internal(index)
    End If
End Property

Public Property Let Item(index As Integer, val As Variant)
    m_internal(index) = val
End Property

Public Property Set Item(index As Integer, val As Object)
    Set m_internal(index) = val
End Property

with the above files...

Dim p As Parent
Set p = New Parent

' these lines are just fine    
Dim pChild As ChildClass
Set pChild = p.Child
pChild(2) = 2

' this throws compilation error "Wrong number of arguments or invalid property assignment"
p.Child(2) = 2

Can you explain why the second option to access the Child internal member's default property is not compiling?


Solution

  • Because you are not using properties. Public Child as New ChildClass is a field.

    Make it a property:

    Private mChild As New ChildClass
    
    Public Property Get Child() As ChildClass
      Set Child = mChild
    End Property
    

    and p.Child(2) = 2 will compile.