I have 20 kids composing of 10 boys in column A and 10 girls in Column B . I need excel vba to choose a pair of boy and girl at random for the 20 kids.
thanks
I have 20 kids composing of 10 boys in column A and 10 girls in Column B . I need excel vba to choose a pair of boy and girl at random for the 20 kids.
thanks
This is overkill, but I slapped it together just together just for fun. It selects a random name from any number of lists (one per column) including colors and sound while choosing.
I just hit double-backspace while about to submit my edit, losing it all, so this is the short version - less information and links.
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
Download sample .XLSM
workbook with these examples here. (File contains VBA/Macros so you may get a security warning when opening.)
You can also do this online (completely without Excel) using RANDOM.ORG.
Formula in C3
:
=OFFSET(C5,RAND()*10,0)
Formula in D3
:
=OFFSET(D5,RAND()*10,0)
Offset Function (Excel)
Rand Function (Excel)