我有20个孩子,A组有10个男孩,B组有10个女孩。我需要excel vba为20个孩子随机选择一对男孩和女孩。
谢谢
这太过分了,但为了好玩,我把它们拼凑在一起。它在选择时从任意数量的列表(每列一个)中选择一个随机名称,包括颜色和声音。
我只是在提交编辑时点击双退格,丢失了所有内容,所以这是短版本 - 更少的信息和链接。
Option Explicit 'always use this!
Const shtName = "RandVBA" 'name of worksheet
Const cellRange = "B5:C14" 'cell range (each column gets separate selection)
Public Declare Function Beep Lib "kernel32" _
(ByVal dwFreq As Long, _
ByVal dwDuration As Long) As Long
Sub chooseRandomColumns()
'selects a random cells from each column in range, with colors and sound
Randomize
Dim cr As Range, col As Range, x As Long, n As Long, winners As String
Set cr = Sheets(shtName).Range(cellRange)
For x = 1 To 20
cr.Cells.Interior.Color = RGB(255, 255, 255) 'reset background colors
winners = "" 'erase winners names
For Each col In cr.Columns
n = Int(Rnd() * cr.Rows.Count) + cr.Row 'pick random cell in column
Sheets(shtName).Cells(n, col.Column).Interior.Color = _
RGB(Int(Rnd() * 256), Int(Rnd() * 256), Int(Rnd() * 256)) 'random color
winners = winners & " - " & Sheets(shtName).Cells(n, col.Column) & vbLf
Next col
Beep Int(Rnd() * 2000) + 300, 125 'random beep 125ms/300-2300Hz
DoEvents 'catch-up
Next x
MsgBox "The winners are:" & vbLf & vbLf & winners, vbExclamation, "Winners!"
End Sub
下载示例.XLSM
工作簿与这些示例here。 (文件包含VBA /宏,因此打开时可能会收到安全警告。)
您也可以使用RANDOM.ORG在线完成(完全没有Excel)。
在C3
的公式:
=OFFSET(C5,RAND()*10,0)
在D3
的公式:
=OFFSET(D5,RAND()*10,0)