EXCEL VBA从1到35的数字当众随机挑选7个且不重复,1到12至少出现一个,13-24至少出现1个,25到35至少出现一个中的数字,将结果放在SHEET2的A列。再从1-12中随机挑选3个数字且不重复,将结果放在SHEET2的B列
时间: 2024-05-30 19:16:45 浏览: 86
EXCEL VBA技巧及实例!
下面是实现该功能的Excel VBA代码:
Sub RandomSelection()
Dim arr() As Integer
ReDim arr(1 To 35)
Dim i As Integer
For i = 1 To 35
arr(i) = i
Next i
'随机打乱数组
Dim j As Integer
Dim temp As Integer
For i = 1 To 35
j = Int(Rnd() * 35) + 1
temp = arr(i)
arr(i) = arr(j)
arr(j) = temp
Next i
'选取数字
Dim num1 As Integer, num2 As Integer, num3 As Integer, num4 As Integer, num5 As Integer, num6 As Integer, num7 As Integer
Dim count1 As Integer, count2 As Integer, count3 As Integer
For i = 1 To 35
If arr(i) <= 12 And count1 < 1 Then
num1 = arr(i)
count1 = count1 + 1
ElseIf arr(i) > 12 And arr(i) <= 24 And count2 < 1 Then
num2 = arr(i)
count2 = count2 + 1
ElseIf arr(i) > 24 And count3 < 1 Then
num3 = arr(i)
count3 = count3 + 1
ElseIf arr(i) <= 12 And num4 = 0 Then
num4 = arr(i)
ElseIf arr(i) <= 12 And num5 = 0 Then
num5 = arr(i)
ElseIf arr(i) <= 12 And num6 = 0 Then
num6 = arr(i)
ElseIf arr(i) <= 12 And num7 = 0 Then
num7 = arr(i)
End If
Next i
'输出结果
Sheets("SHEET2").Range("A1:A7").Value = Array(num1, num2, num3, num4, num5, num6, num7)
'从1-12中随机挑选3个数字且不重复
Dim arr2() As Integer
ReDim arr2(1 To 12)
For i = 1 To 12
arr2(i) = i
Next i
'随机打乱数组
For i = 1 To 12
j = Int(Rnd() * 12) + 1
temp = arr2(i)
arr2(i) = arr2(j)
arr2(j) = temp
Next i
'选取数字
Dim num8 As Integer, num9 As Integer, num10 As Integer
num8 = arr2(1)
num9 = arr2(2)
num10 = arr2(3)
'输出结果
Sheets("SHEET2").Range("B1:B3").Value = Array(num8, num9, num10)
End Sub
在代码中,我们首先创建一个包含1到35的数字的数组,然后随机打乱这个数组。接下来,我们使用一个循环来选取数字。我们首先选取1到12中的一个数字,然后选取13到24中的一个数字,最后选取25到35中的一个数字。如果我们在选取这三个数字时发现某个数字已经被选取过了,我们就跳过这个数字。然后我们再从1到12中随机选取4个数字,但这些数字不能与前面选取的数字重复。最后,我们将这些数字输出到SHEET2的A列和B列中。
阅读全文