我有简单的VBA字典。 Key是一个字符串,Item是一个自定义类(包含简单属性和一些函数)。
我正在遍历我的字典,尝试调用字典中每个类实例(cNewClass)的一个函数。我在这里挣扎:
Dim i As Integer
Dim nt As New cNewClass
a = dict.Items
For i = 0 To dict.Count - 1
nt = a(i)
Next i
在这一行:
nt = a(i)
我收到错误:"对象不支持此属性或方法"。
[编辑:试过这个,没有工作]我可以做点什么吗?:
For i = 0 To dict.Count - 1
a(i).RunMethod(Args)
Next i
谢谢 - KC
答案 0 :(得分:1)
As you noticed,您需要使用Set
关键字来分配对象引用。
Dim i As Integer Dim nt As New cNewClass a = dict.Items For i = 0 To dict.Count - 1 Set nt = a(i) Next i
但是我需要警告你这里有一个令人讨厌的问题:As New cNewClass
正在改变nt
的行为,这可能会或可能不会干扰,但我仍然 警告你:
Sub Test()
Dim c As New Collection
c.Add "Foo"
Set c = Nothing
c.Add "Bar" 'you'd think this would blow up because 'c' is Nothing, right? Think again!
End Sub
当声明本地对象变量As New
时,无论什么内容,VBA都会使引用保持活动状态,可能会引入意外或意外行为。
您未使用您已声明nt
的引用 - 只需放开New
关键字:
Dim i As Integer
Dim nt As cNewClass
a = dict.Items
For i = 0 To dict.Count - 1
Set nt = a(i)
Next i
答案 1 :(得分:0)
答案 - 使用“SET”
Dim i As Integer
Dim nt As New cNewClass
a = dict.Items
For i = 0 To dict.Count - 1
Set nt = a(i)
Next i