2

I am trying to create a list of objects in VBA but it seems like new objects are not being created and values are being updated to a single instance of a class.

This is the class

' ---------------------------------------------------------------
'
' Class to represent Program Increment
'
' ---------------------------------------------------------------

Public name As String

Public sprints As New Collection

This is the calling code:

' get the unique pi values
Dim piList As New Collection
For r = firstRow To lastRow
    currentVal = Cells(r, 2)
    On Error Resume Next
        Dim currentPi As New ProgramIncrement
        currentPi.name = currentVal
        piList.Add currentPi, currentVal
    On Error GoTo 0
Next

This is the output for the first pi enter image description here

And this is the output for the second pi enter image description here

I'm not seeing what I'm doing wrong base upon online documents such as this. https://analystcave.com/vba-vba-class-tutorial/

0

2 Answers 2

7

As New creates an auto-instantiated object. Dim statements aren't executable, so there's only one object indeed.

Remove As New and use Set ... = New statements to create new objects.

Dim currentPi As ProgramIncrement
Set currentPi = New ProgramIncrement

Dim being inside the loop makes no difference - on one hand it makes it easy to later refactor and extract the loop body into its own procedure scope; on the other hand it can be read as though a new variable is created at every iteration, but that's not how scopes work in VBA: the smallest scope is procedure scope - blocks (e.g. loop bodies) don't scope anything.

Sign up to request clarification or add additional context in comments.

Comments

-1

This worked per Mathieu Guindon's answer.

Dim piList As New Collection
Dim currentPi As ProgramIncrement
For r = firstRow To lastRow
    currentVal = Cells(r, 2)
    Set currentPi = New ProgramIncrement
    currentPi.name = currentVal
    On Error Resume Next
        piList.Add currentPi, currentVal
    On Error GoTo 0
Next

1 Comment

Edited to reflect this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.