ExcelBanter

ExcelBanter (https://www.excelbanter.com/)
-   Excel Programming (https://www.excelbanter.com/excel-programming/)
-   -   Shuffling a Data List (https://www.excelbanter.com/excel-programming/324900-shuffling-data-list.html)

Don Lloyd

Shuffling a Data List
 
Is anyone aware of a simple VBA routine to shuffle the contents of a list in
random fashion.

Don



Tushar Mehta

Shuffling a Data List
 
Random Selection
http://www.tushar-mehta.com/excel/ne...ion/index.html

--
Regards,

Tushar Mehta
www.tushar-mehta.com
Excel, PowerPoint, and VBA add-ins, tutorials
Custom MS Office productivity solutions

In article , don.lloyd2
@virgin.net says...
Is anyone aware of a simple VBA routine to shuffle the contents of a list in
random fashion.

Don




Tom Ogilvy

Shuffling a Data List
 
here's another: (assuming the list is in a column - as written, starting in
A1)

Sub Shuffle()
'
' Algorithm from:
' The Art of Computer Programming: _
' SemiNumerical Algorithms Vol 2, 2nd Ed.
' Donald Knuth
' p. 139 [Algorithm P]
'
'
Dim list As Variant
Dim rng As Range
Dim t As Long, j As Long, k As Long
t = 100
Set rng = Range(Cells(1, 1), Cells(1, 1).End(xlDown))
list = rng.Value
t = UBound(list, 1)
j = t
Randomize
For i = 1 To t
k = Rnd() * j + 1
lngTemp = list(j, 1)
list(j, 1) = list(k, 1)
list(k, 1) = lngTemp
j = j - 1
Next
rng.Value = list
End Sub

--
Regards,
Tom Ogilvy

"Don Lloyd" wrote in message
...
Is anyone aware of a simple VBA routine to shuffle the contents of a list

in
random fashion.

Don





Don Lloyd

Shuffling a Data List
 
Than you Tom,

Just the job. I like the use of an array for doing the spadework.

Don

"Tom Ogilvy" wrote in message
...
here's another: (assuming the list is in a column - as written, starting
in
A1)

Sub Shuffle()
'
' Algorithm from:
' The Art of Computer Programming: _
' SemiNumerical Algorithms Vol 2, 2nd Ed.
' Donald Knuth
' p. 139 [Algorithm P]
'
'
Dim list As Variant
Dim rng As Range
Dim t As Long, j As Long, k As Long
t = 100
Set rng = Range(Cells(1, 1), Cells(1, 1).End(xlDown))
list = rng.Value
t = UBound(list, 1)
j = t
Randomize
For i = 1 To t
k = Rnd() * j + 1
lngTemp = list(j, 1)
list(j, 1) = list(k, 1)
list(k, 1) = lngTemp
j = j - 1
Next
rng.Value = list
End Sub

--
Regards,
Tom Ogilvy

"Don Lloyd" wrote in message
...
Is anyone aware of a simple VBA routine to shuffle the contents of a list

in
random fashion.

Don








All times are GMT +1. The time now is 06:10 PM.

Powered by vBulletin® Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
ExcelBanter.com