Excel-VBA 中数组的随机元素

问题描述 投票:0回答:3

我翻遍了互联网,仍然没有找到这个问题的任何解决方案:

我有一个像这样的数组;

Dim PayRate As Variant
PayRate = Array(10, 20, 30)

Cells(i, "E").value = PayRate(Int((2 - 1 + 1) * Rnd + 1))

但这只会给我数组中的 20 和 30(元素 1 和 2),我还想要元素 0 = 10 混合在一起?我怎样才能做到这一点?

arrays vba excel random
3个回答
4
投票

这样就可以了:

Int(Rnd() * 3) + 1

Rnd()
返回从(包括 0)到(不包括 1)的均匀分布随机数。

重要:您必须在模块顶部有

Option Base 1
,这样您的 PayRate 数组的最低界限为 1。看起来您已经给出了问题文本。


0
投票

考虑:

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

我喜欢这个,因为它与数组中的元素数量或从零开始还是从一开始无关。


0
投票
Dim PayRate As Variant

PayRate = Array(10, 20, 30)
indexNumber = Int(Rnd()*3)
Cells(i, "E").value = PayRate(indexNumber)
© www.soinside.com 2019 - 2024. All rights reserved.