jeudi 13 septembre 2018

VBA Excel - Generate real random numbers that check if result exist in given range

I am using following function to create random number and check if the resulting integer is in a given range:

Function RandBetweenInt(Lowest As Long, Highest As Long, Exclude As Range) As Long
Dim R As Long
Dim C As Range
Do
R = Lowest + Int(Rnd() * (Highest + 1 - Lowest))
For Each C In Exclude
If R = C Then Exit For
Next C
Loop Until C Is Nothing

RandBetweenInt = R
Application.Volatile
End Function

After calling the function RandBetweenInt(0, 999, tgt.Range("K1:K1000")) the result is correct, but I see that the resulting number is always the same (f.i 705) if I just close the file and open it again, so there is no a real random generation happening. Even if I create consecutive random numbers, the sequence seems to be always the same (705, 332, 107...).

For me is really important that each time I create the random number the result is really random. Do you have a hint?




Aucun commentaire:

Enregistrer un commentaire