将字典项目存储为类实例 – 对象不支持此属性或方法

我有简单的VBA词典。 Key是一个string,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

正如您注意到的 ,您需要使用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 

当一个局部对象variables声明As New ,VBA保持引用的存在,不pipe是什么,这可能会引入不希望的或意外的行为。

你并没有使用你正在声明的引用 – 只是放开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 

答案 – 使用“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