【发布时间】:2020-03-09 16:02:42
【问题描述】:
背景:
这是对this 最近的一个问题的后续问题,我询问了如何直接从Dictionary 项返回一组Class 模块属性。
我现在已经尝试使用Property Let 和Property Get 填充Private Array 来填充Dictionary。但是,在运行一些测试时我遇到了Error 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
问题:
dict(keyx) = lst 将出现错误 438,并告诉我对象(字典)不支持此 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是一个对象 -
这么简单......谢谢@TimWilliams。愿意张贴作为结束问题的答案吗?我在这上面花了几个小时:S
-
GetArray 不正确。您正在返回一个未声明的变量“vals”。如果您的意图是返回类的私有数组,那么您的代码应该是 getarray=lst。 dict(keyx) 可能应该是 'set dict.item(x)' (我不想省略默认属性)。 arr = dict(keys).GetArray 应该是 arr = dict.item(key).GetArray.
标签: arrays excel vba class dictionary