buidling randomize function that not repeating the same number

  • Thread starter Thread starter thread
  • Start date Start date
T

thread

hi,

is there any functionality in excel that its posible to make randomize
for a certain group of number and the numbers will not return if
appeared already
example
cell1
rnd()*10=>3
cell 2
rnd()*10=>2
cell3
rcd()*10=>3 <= this option will not appear

any idea?
 
The following is a generalized shuffling routine that I have posted in the
past over in the compiled VB newsgroups, but it works fine in the VBA world
of Excel as well. Assign your values to an array and then pass that into the
RandomizeArray subroutine and it will put elements of the array into a
random order and return the randomized elements back in the original array
that was passed to it. So, to read out the randomize list, just read the
array from its lower bound to whatever number of random elements you need
(up to the maximum of the array's upper bound). It only visits *each* array
element *once* so it is quick. The code takes care of running the Randomize
statement one time only (which is all that is necessary).

Sub RandomizeArray(ArrayIn As Variant)
Dim X As Long
Dim RandomIndex As Long
Dim TempElement As Variant
Static RanBefore As Boolean
If Not RanBefore Then
RanBefore = True
Randomize
End If
If VarType(ArrayIn) >= vbArray Then
For X = UBound(ArrayIn) To LBound(ArrayIn) Step -1
RandomIndex = Int((X - LBound(ArrayIn) + 1) * _
Rnd + LBound(ArrayIn))
TempElement = ArrayIn(RandomIndex)
ArrayIn(RandomIndex) = ArrayIn(X)
ArrayIn(X) = TempElement
Next
Else
'The passed argument was not an array
'Put error handler here, such as . . .
Beep
End If
End Sub

After passing your array into the RandomizeArray subroutine, its elements
will be randomly reordered. The passed array may be of any normal type --
integer, string, single, etc. The neat thing is, if you pass an already
randomized array to this routine, those randomly ordered elements will be
randomize -- sort of like shuffling an already shuffled deck of cards.
 
Hi,

You posted in programming so here's a macro. Right click your sheet tab,
view code and paste the code below in and run it.

Change TopNo to the highest value you want and set the range to suit which
is currently A1 - A25. Note the TopNo must be >= to the cells in the range or
they cannot be unique.

Sub Marine()
Dim TopNo As Long
TopNo = 1000
Dim FillRange As Range
Set FillRange = Range("A1:A25")
For Each C In FillRange
Do
C.Value = Int((TopNo * Rnd) + 1)
Loop Until WorksheetFunction.CountIf(FillRange, C.Value) < 2
Next
End Sub


Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top