Home > Mobile >  Cannot access to custom object which added to collection in custom class via method
Cannot access to custom object which added to collection in custom class via method

Time:10-26

I have a custom class List:

Private me_col As New Collection

Public Function GetAt(position As Integer)
    GetAt = me_col(position   1)
End Function

Public Sub Add(value)
    me_col.Add value
End Sub

If I add a list directly to the collection, I can get it via index. The message box will show "List":

Sub Run()
Dim col As New Collection

Dim child As New List

col.Add child
MsgBox TypeName(col(1))
End Sub

But if I try add it to the List via List.Add and GetAt later, the application will throw a Run-time error '438': Object doesn't support this property or method:

Sub Run()
Dim col As New List

Dim child As New List

col.Add child
MsgBox TypeName(col.GetAt(0))
End Sub

This work well with primitive values, only fail on objects such as custom class.

col.Add "a primitive value"
MsgBox TypeName(col.GetAt(0)) 'String

CodePudding user response:

Please, try the next approach:

  1. Adapt the "List" class code in this way:
Option Explicit

Private me_col As New Collection

Public Function GetAt(position As Integer) As Variant
   If IsObject(me_col(position   1)) Then
        Set GetAt = me_col(position   1) 'for the case of an object member (class, collection, sheet etc.)...
    Else
       GetAt = me_col(position   1)
    End If
End Function

Public Sub Add(value)
    me_col.Add value
End Sub
  1. Test it in the next way:
Sub RunList()
 Dim col As New List, child As New List
 child.Add "first item" 'place an item in the first class collection
 
 col.Add child          'place the class inside the class
 col.Add "second item"  'place a string like the second element
 col.Add Array("third item", "fourth item") 'add an array like the third element
 
 MsgBox col.GetAt(0).GetAt(0) 'being a class, you should return the string in the appropriate way...
 MsgBox col.GetAt(1)     'returning the string entry/element
 MsgBox col.GetAt(2)(0)  'returning the first element of the array element...
End Sub

Please, test it, try understanding its meaning and send some feedback.

  • Related