用EXCEL VBA写一段代码吗:从10个数字当中随机挑选8个符合1到33范围内的数字
时间: 2024-05-14 07:13:19 浏览: 213
有用的EXCEL中VBA代码.pdf
当然可以,下面是一段可供参考的代码:
```
Sub RandomSelection()
Dim numbers(1 To 10) As Integer
Dim selectedNumbers(1 To 8) As Integer
Dim i As Integer, j As Integer
Dim randomNumber As Integer
Dim isDuplicate As Boolean
'Fill the numbers array with 10 random integers from 1 to 99
For i = 1 To 10
randomNumber = Int((99 - 1 + 1) * Rnd + 1)
numbers(i) = randomNumber
Next i
'Select 8 numbers from the numbers array that are between 1 and 33
i = 1
Do While i <= 8
randomNumber = Int((33 - 1 + 1) * Rnd + 1)
isDuplicate = False
For j = 1 To i - 1
If selectedNumbers(j) = randomNumber Then
isDuplicate = True
Exit For
End If
Next j
If Not isDuplicate Then
selectedNumbers(i) = randomNumber
i = i + 1
End If
Loop
'Output the selected numbers to the Immediate window
For i = 1 To 8
Debug.Print selectedNumbers(i)
Next i
End Sub
```
这段代码会生成一个长度为10的数组 numbers,里面每个元素都是随机的1到99之间的整数。然后从这个数组中选择8个满足1到33范围内的数(如果有重复的数字,则重新选择),并输出到控制台窗口(可以通过按Ctrl+G打开)。
阅读全文