Reputation: 1381
I created a new class module that looks like this:
Private pNum As Double
Public Property Get Num() As Double
Num = pNum
End Property
Public Property Let Num(Value As Double)
pNum = Value
End Property
I'm trying to add random numbers to a collection, as an object property. This just provides me with 3 objects with the same random number.
Sub Add_number()
Dim rand_num As Cnum
Set rand_num = New Cnum
Dim RandColl As New Collection
Dim numCount As Integer
numCount = 3
Do
RandColl.Add rand_num
rand_num.num = rnd()
Loop Until RandColl.Count = numCount
End Sub
Upvotes: 0
Views: 221
Reputation: 12665
This happens because you are adding every time the same object instance. Write your code like this:
Sub Add_number()
Dim rand_num As Cnum
'Set rand_num = New Cnum '<-- remove the unique initialization from here
Dim RandColl As New Collection
Dim numCount As Integer
numCount = 3
Randomize '<-- also, add the call to the randomize module
Do
Set rand_num = New Cnum '<-- move it in the loop to create a new instance of Cnum each time
RandColl.Add rand_num
rand_num.num = rnd()
Loop Until RandColl.Count = numCount
End Sub
Upvotes: 3