如果我們要用VBA生成一列不重復(fù)的隨機(jī)整數(shù),可以用下面的VBA代碼。本例可以在A1:A100中產(chǎn)生1-100的不重復(fù)隨機(jī)整數(shù)。
Sub RndNumberNoRepeat()
Dim TempArr1(99) As Integer, TempArr2(0 To 99, 1 To 1) As Integer
Dim RndNumber As Integer, i As Integer
Randomize (Timer) ‘初始化隨機(jī)數(shù)生成器
For i = 0 To 99 ‘產(chǎn)生包含1-100的不重復(fù)的隨機(jī)數(shù)列
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中輸入這些數(shù)字
Range("a1:a100").Value = TempArr2
End Sub