Reputation: 786
I have a class called "Transport":
Public Frequency As Double
Public SourceDest As String
Now, I want to read out some cells in Excel and fill a collection with these objects of that class.
Collection:
Dim JobList As New Collection
Sub:
Dim tmp As New Transport
For i = 1 To 20
tmp.Frequency = Round(Frequencies(i), 5)
tmp.SourceDest = Jobs(i)
JobList.Add tmp
Next
Unfortunately, it just adds the same class 20 times, but I want different classes. How can I solve this?
In general, I am new to VBA and all I want is to read two columns in a table, put the "pairs" together (like so: {Double, String}
) in a kind of list {Double, String},{Double, String}, ...
. I tried types before, but apparently they can't be stored in collections, so I chose classes.
Upvotes: 0
Views: 1215
Reputation: 514
In order to create a different object of the class each time you loop, you have to 'tell' VBA to create it inside the loop.
In line 4 a new instance of Transport Class is created in each loop
Dim tmp As Transport
For i = 1 To 20
Set tmp = New Transport
tmp.Frequency = Round(Frequencies(i), 5)
tmp.SourceDest = Jobs(i)
JobList.Add tmp
Next
Upvotes: 3