VBA - 在循环中向集合添加自定义对象

时间:2017-03-17 14:49:14

标签: vba excel-vba object for-loop excel

我创建了一个 Node 对象:

Public value As Integer
Public marked As Boolean

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

然后我尝试在for循环中向一个Collection添加一些节点对象

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)

为什么会这样?

1 个答案:

答案 0 :(得分:2)

你在循环之前错过了一行:

Set arr = New Collection