I currently have a macro that when i click a button, it "randomly" gives me a number in a msgbox:
dim number as double
number= Int(8 * Rnd + 1) - 1
MsgBox number
The thing is, the numbers aren't actually randomized. For example: If i start the macro, click the button twice, lets say i get the numbers 5 and 2. Now if i close the macro and open it again and click the button twice, i get the same two numbers 5 and 2.
Now i know that in VB.net there was a way to actually get it to spit out random numbers each time without repeating the "sequence" but it's been years since i touched vb.net so i don't quite remember, also i would not know how to use it in excel vba.
However, Excel uses what is called a pseudorandom number generator, in this case, the Mersenne Twister algorithm. What that means is that, technically speaking, the numbers that Excel's RAND functions generate aren't truly random.
The Microsoft Excel RND function returns a random number that is greater than or equal to 0 and less than 1. You can use the RND function in a formula to generate a random number within a range of values.
If you want to use RAND to generate a random number but don't want the numbers to change every time the cell is calculated, you can enter =RAND() in the formula bar, and then press F9 to change the formula to a random number.
Example. This example uses the Rnd function to generate a random integer value from 1 to 6. Dim MyValue As Integer MyValue = Int((6 * Rnd) + 1) ' Generate random value between 1 and 6.
You need to initialize the random number function
Sub test()
Dim number As Double
Randomize
number = Int(8 * Rnd + 1) - 1
MsgBox number
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With