[英]Random element from array in Excel-VBA
我已經沖進互聯網,仍然沒有找到這個問題的任何解決方案:
我有一個這樣的數組;
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 混合? 我怎么會那樣做?
這樣做: Int(Rnd() * 3) + 1
Rnd()
返回一個從 0 到不包括 1 的均勻分布的隨機數。
重要提示:您必須在模塊頂部有Option Base 1
,因此您的 PayRate 數組的最低界限為 1。似乎您已經給出了問題文本。
考慮:
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
我喜歡這個,因為它與數組中元素的數量無關,或者它是從零開始還是從一開始。
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.