【问题标题】:Storing Dictionary Item as Class Instance - Object Doesn't Support This Property or Method将字典项存储为类实例 - 对象不支持此属性或方法
【发布时间】:2016-04-19 16:43:34
【问题描述】:

我有简单的 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

【问题讨论】:

    标签: excel vba


    【解决方案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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-09
        • 2013-10-05
        • 1970-01-01
        • 2015-08-18
        • 2015-07-02
        • 2019-04-09
        • 2013-03-23
        相关资源
        最近更新 更多