patternModerate
Generating Random RGB Colors
Viewed 0 times
randomrgbgeneratingcolors
Problem
I have a function for generating RGB colors in VB6.0, and it is working properly. Please suggest improvements for this, if any.
Public Function RandomRGBColor() As Long
RandomRGBColor = RGB( _
Int(Rnd() * 256), _
Int(Rnd() * 256), _
Int(Rnd() * 256))
End FunctionSolution
You need to change/add just one little thing. You need to call the
If you don't do this you will get for each iteration the same "random" number.
Don't get me wrong, this doesn't mean that all numbers will be the same but assume you start your application. For example you will get the RGB numbers
To prevent this, you need to 'seed' the
Randomize () method before using the Rnd () method. You should only call it once, so it would be good, to call the Randomize() method inside of the constructor of your class like:Private Sub Class_Initialize()
Randomize
End SubIf you don't do this you will get for each iteration the same "random" number.
Don't get me wrong, this doesn't mean that all numbers will be the same but assume you start your application. For example you will get the RGB numbers
11, 54, 142 for the first call of your method. If you restart your application you will again get these same numbers on the first call.To prevent this, you need to 'seed' the
Rnd () method to get random values each time.Code Snippets
Private Sub Class_Initialize()
Randomize
End SubContext
StackExchange Code Review Q#59071, answer score: 10
Revisions (0)
No revisions yet.