Private Sub Command1_Click()
Dim a(9) As Long, i As Integer, b() As Long
Cls
For i = 0 To 9
a(i) = i
Next
b = RandomSelect(a, 7)
For i = 0 To 6
Print b(i)
Next
End Sub
Function RandomSelect(ByRef Arr() As Long, ByVal Need As Long) As Long()
Dim Low As Long ' 数组下标
Dim Result() As Long ' 临时数组, 用于返回数据
Dim Count As Long ' 临时数组中有效数据个数
Dim Rand As Long ' 随机数
Result = Arr ' 复制数组以便于修改时不破坏原数据
Low = LBound(Arr) ' 得到数组下标
Count = UBound(Arr) - Low + 1 ' 得到数组元素个数
Randomize
Do While Count > Need ' 如果还有多余的数据
Rand = CLng(Int(Rnd() * Count)) ' 随机选择一个并去掉 (用最后的一个元素填充)
Result(Low + Rand) = Result(Low + Count - 1)
Count = Count - 1 ' 将元素个数减 1
Loop
' 重新定义数组大小并返回
ReDim Preserve Result(Low To Low + Count - 1)
RandomSelect = Result
End Function
温馨提示:答案为网友推荐,仅供参考