Excel VBA Rnd实际上不是随机的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26281011/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA Rnd Not Actually Random
提问by HumanlyRespectable
I currently have a macro that when i click a button, it "randomly" gives me a number in a msgbox:
我目前有一个宏,当我单击一个按钮时,它会“随机”在 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.
问题是,这些数字实际上并不是随机的。例如:如果我启动宏,单击按钮两次,假设我得到数字 5 和 2。现在如果我关闭宏并再次打开它并单击按钮两次,我得到相同的两个数字 5 和 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.
现在我知道在 VB.net 中有一种方法可以让它每次都吐出随机数而不重复“序列”但是我接触 vb.net 已经好几年了所以我不太记得了,我也会不知道如何在excel vba中使用它。
回答by ruedi
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