文章提供三個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