Thread: Random
View Single Post
  #4   Report Post  
Posted to microsoft.public.excel.programming
Rick Rothstein \(MVP - VB\) Rick Rothstein \(MVP - VB\) is offline
external usenet poster
 
Posts: 2,202
Default Random

Thanks for replying. Usually, repeats are not wanted in a small
series.
In this case number 1 to 5.

Sub rndNo()
Dim str As String

For i = 1 To 5
str = str & Int((5 - 1 + 1) * Rnd + 1) & vbCrLf
Next i

MsgBox str
End Sub

I need to favour a certain number i.e. 3 so it would come out more
often,
in this series of 11 quess' and be displayed across Cols B1 to L1


You might try code something like this...

Dim X As Long
Dim Choices As Variant
Choices = Array(1, 3, 2, 3, 3, 3, 4, 3, 5, 3)
For X = 0 To 10
Range("B1").Offset(0, X).Value = _
Choices(Int((1 + UBound(Choices) - LBound(Choices)) * Rnd))
Next

What I have done is placed the numbers 1 through 5 into an array named
Choices; however, I added extra 3's into the mix. The numbers I assigned to
the array are the 10 numbers 1,3,2,3,3,3,4,3,5,3. The code works by
generating a random array index (0 to 9) and assigning the array's value at
that random index to the cells you indicated. This should make assigning the
number 3 a little more than twice as likely as any of the other numbers. You
can adjust the likelihood of the number 3 coming by varying how many extra
ones of them you place in the array via the Array function (the rest of the
code will adjust automatically around this assignment). By the way, the
order you assign values to the elements of the Choices array is immaterial
as you will randomly be picking the index numbers.

Rick