Tom291
Tom291

Reputation: 519

VBA - Adding a custom object to a collection in a loop

I have create a Node Object:

Public value As Integer
Public marked As Boolean

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

Then I tried to add some Node Objects to a Collection in a for loop:

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

But when I try to run it it only says:

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

Why is that happening?

Upvotes: 1

Views: 2236

Answers (1)

Rory
Rory

Reputation: 34075

You're missing a line before your loop:

Set arr = New Collection

Upvotes: 2

Related Questions