Rnd (Random) in VBA

  • Thread starter Thread starter Pepe
  • Start date Start date
P

Pepe

Hello. I'd like to use a Random number generator to provide a number
from 1 to 6. I would then have the result 'posted' to cell "B2".

If the result is a 6, I would have another random number from 1 to 6
generated that would be 'posted' to cell "B3" (offset B2 by 1). This
would continue on as long as the result comes back to be 6 for each
new random number. (Does that make sense) If the results are
anything but 6, then the chain would end.

Result 1 = 6 (Cell B2 = 6) new Random Generated number for cell B3
(Result 2)
Result 2 = 6 (Cell B3 = 6) new Random Generated number for cell B4
(Result 3)
Result 3 = 6 (cell B4 = 6) " "
and so on and so forth.

Sorry for the repetitiveness of the data. I wanted to make sure it was
clear.

Thanks for any assistance.

Paul
 
In this example, Rnd will result in a number between 0 and 1, so to ge
a single random digit you must multiply by 10, so to get a numbe
between 1 and 6 you'll have to multiply by 7.

Randomize
For x = 1 To 5
MyValue = Int(Rnd * 10)
Cells(x, 1).Value = MyValue
Next x

- Piku
 
Sub GenRand()
Dim lngNum As Long
Dim i As Long
Range("B2:B200").ClearContents
i = 2
Do
lngNum = Rnd() * 6 + 1
Cells(i, 2).Value = lngNum
i = i + 1
Loop While lngNum = 6

End Sub
 
Thanks for the quick replies. Tom, yours did the trick. The only thing
I changed was to adjust
lngNum = Rnd() * 6 + 1
to
lngNum = Rnd() * 5 + 1.

This gives me my random between 1 and 6. The first method gave me up to
7.

This was great. As usual, you are a big help.

Paul
 
I got too cute and forgot that the implicit conversion rounds the number.
Try it this way.

Sub GenRand()
Dim lngNum As Long
Dim i As Long
Range("B2:B200").ClearContents
i = 2
Do
lngNum = Int(Rnd() * 6 + 1)
Cells(i, 2).Value = lngNum
i = i + 1
Loop While lngNum = 6
Next j
End Sub
 
Hello to all

two point
1)
Some times the int() function does not round correctly.
Use Fix()...

2)
To insure you get a different list of numbers each time
use Randomize Timer

Giving:

Public Sub fillRandom
Dim intNumber As Integer
Dim intRow As Integer
'
Range("B2:B200").ClearContents
intRow = 1
Randomize Timer
Do
intNumber = Fix(Rnd() * 6 + 1)
Cells(intRow, 2).Value = intNumber
intRow = intRow + 1
Loop Until intNumber = 6
End Sub
 
Int and Fix only differ when dealing with negative numbers. for positive
numbers, the case here, neither round - they both truncate.

While there is nothing wrong with using randomize, I wouldn't see it as
required here. If you don't specify a specific seed, you are not going to
get repeated numbers for sequences less than the period of the generator.
 

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