【问题标题】:VBA - Adding a custom object to a collection in a loopVBA - 在循环中将自定义对象添加到集合中
【发布时间】:2017-03-17 14:49:14
【问题描述】:

我已经创建了一个 Node 对象:

Public value As Integer
Public marked As Boolean

Private Sub Class_Initialize()
     value = 0
     marked = False
End Sub

然后我尝试在 for 循环中将一些 节点对象 添加到集合中:

Dim inp As Integer
Dim counter As Integer
Dim n As node
Dim arr As Collection

Sub MySub()

    inp = InputBox("Insert a number: ")

    For counter = 2 To inp
        Set n = New node
        With n
            .value = counter
            .marked = False
        End With
        arr.Add n
    Next counter

End Sub

但是当我尝试运行它时,它只会说:

Object variable or With block variable not set (Error 91)

为什么会这样?

【问题讨论】:

  • 您缺少Set arr = New Collection 行。
  • @Rory 哇,谢谢,这很简单.....把它写成答案,这样我就可以打勾了:)

标签: vba excel object for-loop


【解决方案1】:

你在循环之前少了一行:

Set arr = New Collection

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 2021-07-25
    • 2016-03-17
    相关资源
    最近更新 更多