用EXCEL VBA写一段代码吗:从A1:A10当中随机挑选8个符合1到33范围内的数字,将数字输出到B1:B8,没被挑选到的数字输出到B10:B11
时间: 2024-05-21 09:13:21 浏览: 13
可以的,以下是代码:
Sub RandomNumbers()
'设置随机数种子
Randomize
'定义变量
Dim i As Integer
Dim j As Integer
'定义数组
Dim arr(1 To 10) As Integer
'将1到33的数字存入数组
For i = 1 To 33
arr(i) = i
Next i
'循环8次,从数组中随机取出一个数字,并将其赋值给B列单元格
For i = 1 To 8
j = Int((33 - i + 1) * Rnd + i)
Range("B" & i) = arr(j)
arr(j) = arr(i)
Next i
'输出剩余的数字
For i = 1 To 2
Range("B" & 10 + i) = arr(33 - i)
Next i
End Sub
希望能帮到你!
相关问题
用EXCEL VBA写一段代码吗:从10个指定数字当中随机挑选8个符合1到33范围内的数字
当然可以!以下是一个简单的Excel VBA代码,可以从给定的10个数字中随机选择8个数字,只选择1到33范围内的数字:
Sub RandomSelection()
Dim arr(1 To 10) As Integer
Dim i As Integer
'给定10个数字
arr(1) = 1
arr(2) = 2
arr(3) = 3
arr(4) = 4
arr(5) = 5
arr(6) = 6
arr(7) = 7
arr(8) = 8
arr(9) = 9
arr(10) = 10
'随机选择8个数字
For i = 1 To 8
Randomize
num = Int((10 - i + 1) * Rnd + i)
While arr(num) < 1 Or arr(num) > 33
Randomize
num = Int((10 - i + 1) * Rnd + i)
Wend
MsgBox arr(num)
arr(num) = -1
Next i
End Sub
希望这可以帮助你!
用EXCEL VBA写一段代码吗:从10个数字当中随机挑选8个符合1到33范围内的数字
当然可以,下面是一段可供参考的代码:
```
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打开)。