samedi 7 décembre 2019

Shuffle sequence not working for random numbers using vba

VBA program to shuffle numbers working fine when data is in sequence like 1,2,3,4,5 or 1,4,3,2,5 but when doing it in random form 1,2,4,6,7 it automatically changes the sequence to 1,2,3,4,5 and gives random samples related to it. Here is sample

enter image description here

Now when I click on button1 it will randomize the sequence but change numbers to 1,2,3,4,5enter image description here

Here is my code though I am new to 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



Aucun commentaire:

Enregistrer un commentaire