在属性的集合随机数中分配新对象-VBA

时间:2019-02-26 19:03:28

标签: excel vba

我创建了一个新的类模块,如下所示:

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

我正在尝试向对象属性中添加随机数。 这只是为我提供了3个具有相同随机数的对象。

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

1 个答案:

答案 0 :(得分:3)

之所以会这样,是因为您每次都添加相同的对象实例。 像这样编写代码:

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