随机播放序列不适用于使用VBA的随机数

时间:2019-12-08 07:19:00

标签: excel vba random

VBA程序可以在数据按顺序排列为1,2,3,4,5或1,4,3,2,5时以随机形式工作1,2,4,6, 7它会自动将序列更改为1,2,3,4,5并给出与其相关的随机样本。这是样品

enter image description here

现在,当我单击button1时,它将随机化序列,但将数字更改为1,2,3,4,5 enter image description here

这是我的代码,尽管我是vba的新手

Private Sub ShuffleArray(mArray() As Integer, iUbound As Integer)

    Dim iTop As Integer
    Dim iTemp As Integer
    Dim iSlot As Integer

    'first build it up
    ReDim mArray(iUbound)
    For iTemp = 1 To iUbound
        mArray(iTemp) = iTemp
    Next iTemp

    'now shuffle it
    For iTop = iUbound To 2 Step -1
        iTemp = mArray(iTop)
        iSlot = Int((iTop - 1) * Rnd + 1)
        mArray(iTop) = mArray(iSlot)
        mArray(iSlot) = iTemp
    Next iTop

End Sub

Sub RandomizeOrder()

    Dim iCities As Integer

    iCities = Sheet1.Range("X1048576").End(xlUp).Row - 2

    If iCities < 2 Or iCities > 100 Then MsgBox "Invalid number or cities", vbCritical: Exit Sub

    Dim mArray() As Integer
    Dim iA As Integer

    ShuffleArray mArray, iCities

    For iA = 1 To iCities
        Sheets("distances").Cells(iA + 2, 24).Value = mArray(iA) - 1
    Next iA

End Sub

1 个答案:

答案 0 :(得分:3)

使用Rnd时,您还需要在VBA中利用Randomize功能

'now shuffle it
For iTop = iUbound To 2 Step -1
    iTemp = mArray(iTop)
    Randomize ' <--- add this here
    iSlot = Int((iTop - 1) * Rnd + 1)
    mArray(iTop) = mArray(iSlot)
    mArray(iSlot) = iTemp
Next iTop

警告::如果在调用Rnd函数之前未调用Randomize函数,则Rnd函数可能每次都返回相同的随机数值。因此,您可能无法获得真正的随机数。

相关问题