EXCEL VBA从1到35的数字当众随机挑选7个且不重复,1到12至少出现一个,13-24至少出现1个,25到35至少出现一个中的数字,将结果放在SHEET2的A列。从1-12中随机挑选3个数字且不重复,将结果放在SHEET2的B列
时间: 2024-06-01 10:10:12 浏览: 131
Sub RandomNumbers()
Dim arrNumbers(1 To 35) As Integer
Dim arrResult(1 To 7) As Integer
Dim arrBonus(1 To 3) As Integer
Dim i As Integer, j As Integer, k As Integer, n As Integer
Dim temp As Integer, bonusCount As Integer
'将1到35的数字存入数组
For i = 1 To 35
arrNumbers(i) = i
Next i
'将数组中的数字随机排序
For i = 1 To 35
j = Int(Rnd() * 35) + 1
temp = arrNumbers(i)
arrNumbers(i) = arrNumbers(j)
arrNumbers(j) = temp
Next i
'从1到12中至少选一个数字
arrResult(1) = Int(Rnd() * 12) + 1
'从13到24中至少选一个数字
arrResult(2) = Int(Rnd() * 12) + 13
'从25到35中至少选一个数字
arrResult(3) = Int(Rnd() * 11) + 25
'随机选取4到7个数字
For i = 4 To 7
Do
n = Int(Rnd() * 35) + 1
Loop Until Not IsInArray(arrResult, n, i - 1)
arrResult(i) = n
Next i
'将结果存入Sheet2的A列
For i = 1 To 7
Cells(i, 1).Value = arrResult(i)
Next i
'从1到12中随机选取3个数字
For i = 1 To 3
Do
n = Int(Rnd() * 12) + 1
Loop Until Not IsInArray(arrBonus, n, i - 1)
arrBonus(i) = n
Next i
'将结果存入Sheet2的B列
For i = 1 To 3
Cells(i, 2).Value = arrBonus(i)
Next i
End Sub
Function IsInArray(arr As Variant, val As Variant, endIndex As Integer) As Boolean
Dim i As Integer
For i = 1 To endIndex
If arr(i) = val Then
IsInArray = True
Exit Function
End If
Next i
IsInArray = False
End Function
阅读全文