Error 438 Object doesn't support this property or method - Class Object with Dictionary

后端 未结 3 2043
醉酒成梦
醉酒成梦 2021-01-25 00:44

Background:

This is a follow-up question on this recent question I asked on how to return an array of Class module prop

3条回答
  •  死守一世寂寞
    2021-01-25 01:07

    The OP code has quite a few typos, undeclared variables and usable but not 'correct' property Let/Get. This is how I would write the code of the op. Having now been well trained by the code inspections of the fantastic RubberDuck addin I no longer use 'default' properties but ensure that I use the fully qualified name.

    Class code

    Option Explicit
    
    Private Type Properties
    
        List                                As Variant
    
    End Type
    
    Private p                               As Properties
    
    
    Public Sub Class_Initialize()
    
        ReDim p.List(2)
    
    End Sub
    
    
    Public Property Let Item(ByVal i As Long, ByVal NewVal As Variant)
        p.List(i) = NewVal
    End Property
    
    Public Property Get Item(ByVal i As Long) As Variant
        Item = p.List(i)
    End Property
    

    ' Typically VBA uses the plural of the 'item name' when returning the array.

    Public Function Items() As Variant
        Items = p.List
    End Function
    

    Module code

    Sub Test()
    
    Dim x As Long, arr As Variant, lst As Class1
    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
    
        For x = 1 To 3
            Set lst = New Class1
            lst.Item(0) = x
            lst.Item(1) = x
            lst.Item(2) = x
            dict.Add x, lst
        Next x
    
        For x = 4 To 3 Step -1
            If dict.Exists(x) = False Then
                Set lst = New Class1
                lst.Item(0) = x
                lst.Item(1) = x
                lst.Item(2) = x
                dict.Add x, lst
            Else
    
                With dict.Item(x)
    
                    .Item(1) = lst.Item(1) + 2
                    .Item(2) = lst.Item(2) + 2
    
                End With
    
            End If
    
        Next x
    
    Dim myKey                       As Variant
    
        For Each myKey In dict.Keys
            arr = dict.Item(myKey).GetArray
        Next Key
    
    End Sub
    

提交回复
热议问题