I want to generate an unpredictable random integer number but i dont know how. Below is my function to generate between (1 to 8)which keeps returning '6' on first run which is predicted and also, i dont want the numbers to repeat itself.

Private Function RandomIt(Hv As long, Lv As long) As long
RandomIt = Int((Hv - Lv + 1) * Rnd + Lv)
End Function

Please can someone help me out as i want to resume my work urgently.
Thank you.

7 Years
Discussion Span
Last Post by kcasmir

Hi... if you want to get a special number on every start, try to add this line on first row of your fnc:

Randomize Timer

If you'd like to get unique numbers, e.g. for some series numerical, you probably have to make an array, a loop and shoud use it like this way:

Lv = 1
Hv = 8
Dim arrNumbers(Hv) As Boolean

'here comes some of your code where the function is used

Private Function RandomIt(Hv As Long, Lv As Long) As Long
Dim iX As Integer
Dim bExists As Boolean, bAdded As Boolean
    Randomize Timer
    Do Until bAdded = True
        RandomIt = Int((Hv - Lv + 1) * Rnd + Lv)
        For iX = Lv To Hv
            If arrNumbers(RandomIt) = True Then bExists = True: Exit For
        Next iX
        If bExists = False Then
            arrNumbers(RandomIt) = True
            bAdded = True
        End If
End Function

You only have to take care about the counting the function uses. If you run it more times than the space between Lv and Hv is, it will end in an infinite loop... :-) And as you know, it takes a long time to do the infinite loop. My 486 does an infinite loop in 4,86 seconds :-)

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.