返回首页
当前位置: 主页 > Excel教程 > Excel函数教程 >

Excel三个vba生成不重复随机整数的案例

时间:2014-04-02 23:33来源:Office教程学习网 www.office68.com编辑:麦田守望者

文章提供三个vba代码生成不重复随机数的案例供学习。

vba不重复随机数案例一:
下面的代码,将在A1:A5000单元格产生1-5000的不重复随机整数。
Private Sub vba不重复随机数()
Dim Arr1(1 To 5000) As Boolean
Dim Arr2(1 To 5000, 0) As Integer
t = Timer
[A:A] = Empty
For i = 1 To 5000
num = Int(5000 * Rnd + 1)
Do While Arr1(num)
num = Int(5000 * Rnd + 1)
Loop
Arr1(num) = True
Arr2(i, 0) = num
Next i
[A1:A5000] = Arr2
End Sub


vba不重复随机数案例二:
在A1:A100中产生1-100的不重复随机整数,代码如下:
Sub vba不重复随机数()
Dim TempArr1(99) As Integer, TempArr2(0 To 99, 1 To 1) As Integer
Dim RndNumber As Integer, i As Integer
Randomize (Timer) '初始化随机数生成器
For i = 0 To 99 '产生包含1-100的不重复的随机数列
TempArr1(i) = i
Next i
For i = 99 To 0 Step -1
RndNumber = Int(i * Rnd)
TempArr2(99 - i, 1) = TempArr1(RndNumber) + 1
TempArr1(RndNumber) = TempArr1(i)
Next i
'在A1:A100中输入这些数字
Range("a1:a100").Value = TempArr2
End Sub


vba不重复随机数案例三:
在A1:A10单元格产生10个0-100的随机整数,以下是代码:
Sub vba不重复随机数()
Dim i As Long
i = 100
Dim num As Long
ReDim arr(i) As Long
ReDim Arr2(i, 0) As Long
Dim x As Long
For x = 0 To i
arr(x) = x
Next x
For x = 0 To i
num = Int(Rnd() * (i - x))
Arr2(x, 0) = arr(num)
arr(num) = arr(i - x)
Next x
Range("A1:A10") = Arr2
End Sub

 

------分隔线----------------------------
标签(Tag):excel excel2007 excel2010 excel2013 excel2003 excel技巧 excel教程 excel实例教程
------分隔线----------------------------
推荐内容
猜你感兴趣