[英]Random element from array in Excel-VBA
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 ?但这只会给我 20 和 30 来自数组(元素 1 和 2),我还想要元素 0 = 10 混合? How do I got about doing that?
我怎么会那样做?
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。似乎您已经给出了问题文本。
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.我喜欢这个,因为它与数组中元素的数量无关,或者它是从零开始还是从一开始。
Dim PayRate As Variant
PayRate = Array(10, 20, 30)
indexnumber= Int(Rnd()*3
Cells(i, "E").value = PayRate(indexnumber)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.