vba Excel-VBA中数组中的随机元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19117707/
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
Random element from array in Excel-VBA
提问by Thatdude1
I've stormed the internet and still have not found any solution to this question:
我已经冲进互联网,仍然没有找到这个问题的任何解决方案:
I have an array like so;
我有一个这样的数组;
Dim PayRate As Variant
PayRate = Array(10, 20, 30)
Cells(i, "E").value = PayRate(Int((2 - 1 + 1) * Rnd + 1))
but this will only give me 20 and 30 from the array (elements 1 and 2), I also want element 0 = 10 in the mix ? How do I got about doing that?
但这只会给我 20 和 30 来自数组(元素 1 和 2),我还想要元素 0 = 10 混合?我怎么会那样做?
回答by Bathsheba
This will do it: Int(Rnd() * 3) + 1
这将做到: Int(Rnd() * 3) + 1
Rnd()
returns a uniformly distributed random number from and including 0 to and not including 1.
Rnd()
返回一个从 0 到不包括 1 的均匀分布的随机数。
Important: you must have Option Base 1
at the top of the module so your PayRate array has lowest bound of 1. Seems like you have this given your question text.
重要提示:你必须Option Base 1
在模块的顶部,所以你的 PayRate 数组的最低界限是 1。似乎你有这个给你的问题文本。
回答by Gary's Student
Consider:
考虑:
Sub dural()
Dim PayRate As Variant
PayRate = Array(10, 20, 30)
i = 1
N = Application.WorksheetFunction.RandBetween(LBound(PayRate), UBound(PayRate))
Cells(i, "E").Value = PayRate(N)
End Sub
I like this because it is independent of the number of elements in the array or whether it is zero-based or one-based.
我喜欢这个,因为它与数组中元素的数量无关,或者它是从零开始还是从一开始。