View Single Post
  #4   Report Post  
Posted to microsoft.public.excel.programming
Tom Ogilvy Tom Ogilvy is offline
external usenet poster
 
Posts: 27,285
Default Rnd (Random) in VBA

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.

--
Regards,
Tom Ogilvy



"Wouter" wrote in message
om...
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


"Tom Ogilvy" wrote in message

...
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

--
Regards,
Tom Ogilvy


"Paul LaPlant" wrote in message
...
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



*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!