背景:
这是关于 this 的后续问题最近我问了一个关于如何直接从 Dictionary
项返回 Class
模块属性数组的问题。
我现在已经尝试使用 Property Let
和 Property Get
来填充 Private Array
来填充 Dictionary
与。但是,在运行一些测试时我遇到了 错误 438
。
代码:
将 TstClass
想象成一个具有以下代码的类模块:
Private lst(0 To 2) As Variant
Public Property Let Add(ByVal i As Long, ByVal NewVal As Variant)
lst(i) = NewVal
End Property
Public Property Get Val(ByVal i As Long) As Variant
Val = lst(i)
End Property
Public Function GetArray() As Variant
GetArray = vals
End Function
然后这段代码在模块中测试:
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.Add(0) = x
lst.Add(1) = x
lst.Add(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.Add(0) = x
lst.Add(1) = x
lst.Add(2) = x
dict.Add x, lst
Else
Set lst = dict(x)
lst.Add(1) = lst.Val(1) + 2
lst.Add(2) = lst.Val(2) + 2
dict(x) = lst '< Error 438 on this line
End If
Next x
For Each key In dict.keys
arr = dict(keys).GetArray
Next key
End Sub
问题:
错误 438 将发生在 dict(keyx) = lst
上并告诉我对象(字典)不支持此 Property
或 Method
。这个问题对我来说似乎很狡猾,因为 lst
对象在 dict.Add x, lst
上似乎不是问题。事实上,像这样通过 Key
改变 Item
的方法似乎很 common练习。
问题:
而像 Dict.Add x, "Hello"
然后 Dict(x) = "Hello World"
似乎可以工作。代码在第二种方法中使用 Class
对象时出错。有谁知道为什么,如果是,如何处理这个问题?
谢谢, JvdV
最佳答案
Set dict(keyx) = lst
由于变量lst
引用了一个对象,所以这里需要Set
。
关于arrays - 错误 438 对象不支持此属性或方法 - 带字典的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58844187/