Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA Rnd Not Actually Random

Tags:

excel

vba

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.

like image 833
HumanlyRespectable Avatar asked Oct 09 '14 14:10

HumanlyRespectable


People also ask

Is Excel Rand truly random?

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.

What is RND in Excel VBA?

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.

How do I stop random data from changing in Excel?

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.

How do I use the rand function in VBA?

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.


1 Answers

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
like image 83
ruedi Avatar answered Oct 09 '22 13:10

ruedi