hello,
How can i generate unique random number in vb.I mean during the execution of application numbers ain't repeated. need code
thanks
Ashish
Printable View
hello,
How can i generate unique random number in vb.I mean during the execution of application numbers ain't repeated. need code
thanks
Ashish
in your app do you store the generated numbers after use? You will need to store them when they are generated, so that each time it attempts to generate a number, it can check the list to see if it has already been used, if so it should generate a new one and check again etc...
There should also be a check in the loop for the number of iterations. If the random number runs from 1-100, for example, after the 100th time the program will loop forever.
Randomize
i = CInt(rnd*100000)
Will generate a random integer between 0 and 100000, for example
If you want it to be unique, then you'd need to store the previous ones :)
This will generate 9 unique numbers (in this case up to 9999)
VB Code:
Dim nTry As Integer Dim MyCollection As New Collection Randomize Do While MyCollection.Count < 10 nTry = Int(10000 * Rnd) ' If the number is already in the collection an error is generated ' so it is not added On Error Resume Next MyCollection.Add CStr(nTry), CStr(nTry) Loop