不重复读取一个数组(用100个变量来做选取标志):
Public Sub ShowRnd()
'NumCount 为原始数组维数,SelCount 为随机数组维数
Const NumCount = 100, SelCount = 100
'NumAry 为原始数组,GetAry 为随机数组,selAry 数组存储已取过的数组下标
Dim NumAry(NumCount) As Long, GetAry(SelCount) As Long, selAry(SelCount) As Long
Dim i As Long, j As Long
'为原始数组赋值
For i = 1 To NumCount
NumAry(i - 1) = i * 10 '也可以赋其它值或字段值
Next
'为随机数组取值
For i = 0 To SelCount - 1
Do
selAry(i) = Int(Rnd() * NumCount) '取新下标
'逐个与已取过的数组下标比较
For j = 0 To i - 1
If selAry(i) = selAry(j) Then '重复取值
Exit For
End If
Next j
If j = i Then Exit Do '如果 j<i, 则重新执行循环,再取新下标
Loop
GetAry(i) = NumAry(selAry(i)) '用取得的新下标为随机数组赋值
if SelCount<100 then Debug.Print GetAry(i) '在调试窗口显示随机数组的值
Next i
Debug.Print "Finish" '随机数组取值完成
End Sub
Private Sub 命令0_Click()
Const AllCount = 100, GetCount = 50
Dim a(1 To AllCount) As Long
Dim i, Temp, RndNum As Long
'赋值给数组
For i = 1 To AllCount
a(i) = i
Next
'给数组随机排序
For i = 1 To GetCount
RndNum = Int(Rnd * (AllCount + 1 - i)) + i '产生一个i到100之间的随机数
Temp = a(i)
a(i) = a(RndNum)
a(RndNum) = Temp
Debug.Print a(i)
Next i
End Sub