shuffle array values

jgnasser

Registered User.
Local time
Today, 07:31
Joined
Aug 25, 2003
Messages
54
Forum, I have an array that has 821 values. I need to shuffle this array so that the elements are rearranged randomly without being repeated. I have seen a couple of codes which claim to do just this but do not seem to work well, I end up with some values missing. One such code is here. Anyone know a more robust code that will do this for me?

Function ArrayShuffle(arr As Variant)
Dim index As Long
Dim newIndex As Long
Dim firstIndex As Long
Dim itemCount As Long
Dim tmpValue As Variant

firstIndex = LBound(arr)
itemCount = UBound(arr) - LBound(arr) + 1

For index = UBound(arr) To LBound(arr) + 1 Step -1
' evaluate a random index from LBound to INDEX
newIndex = firstIndex + Int(Rnd * itemCount)
' swap the two items
tmpValue = arr(index)
arr(index) = arr(newIndex)
arr(newIndex) = tmpValue
' prepare for next iteration
itemCount = itemCount - 1
Next
ArrayShuffle = arr
End Function
 
Before you use the Rnd function you need to seed it by using the Random function. A typical seed value would be the value of Now() which contains the current date and time.
 

Users who are viewing this thread

Back
Top Bottom