vba 如何从 Visual Basic 中的数组中选择一个随机元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14310272/
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
How to choose a random element from an array in Visual Basic
提问by ShuklaSannidhya
I have created an array of Integer and want to choose a random element from it. How do I do that?
我创建了一个整数数组,并想从中选择一个随机元素。我怎么做?
回答by beezir
YourArray(New Random().Next(0,YourArray.Length-1))
Or separated out for more clarity:
或者为了更清楚而分开:
Dim Rand as New Random()
Dim Index as Integer = Rand.Next(0, YourArray.Length - 1)
Dim SelectedValue = YourArray(Index)
回答by Tony Stark
Rnd can get [0,1),then mutiple Your arraylength, you can get number between [0,YourArrayLength)
Rnd 可以得到[0,1),那么multiple你的arraylength,你可以得到[0,YourArrayLength)之间的数
Randomize
Int(array.length* Rnd)
回答by dasblinkenlight
Make a random integer number in the range from 0
to Len-1
, where Len
is the length of your array. To make a random integer, use an instance of the Random
class.
在从0
到的范围内创建一个随机整数Len-1
,其中Len
是数组的长度。要生成随机整数,请使用Random
类的实例。
DIM rand As New Random
DIM idx as rand.Next(0, Len)
REM Now you can pick an element idx from the array
REM to get a random element.
DIM res as myArray(index)