View Single Post
  #5   Report Post  
 
Posts: n/a
Default Random Date Generation

Hello,

Time out? Never happened to me.

Anyway, the function is:

Option Explicit

'If lRange n then set LATE_INITIALISATION to true
'For example if lRange=1000000 and if 1000 cells are selected (n=1000)
#Const LATE_INITIALISATION = False
'If random integers may occur more than once, allow repetitions
#Const ALLOW_REPETITION = True

Public Function UniqRandInt(ByVal lRange As Long, _
Optional ByVal lMaxOccurence As Long = 1) As Variant

'Returns n unique (=non-repeating) random ints within 1..lRange,
'lRange = n if n cells in a worksheet have been selected and the
'function has been entered as array formula (CTRL+SHIFT+ENTER).
'Set lMaxOccurences 1 if random integers may occur more than once.

'Algorithm by: sulprobil http://Reverse("moc.liborplus.www")

Dim vA As Variant
Dim vR As Variant
Dim i As Long
Dim lr As Long
Dim lRow As Long
Dim lCol As Long

Application.Volatile

If TypeName(Application.Caller) < "Range" Then
UniqRandInt = CVErr(xlErrRef)
Exit Function
End If

#If ALLOW_REPETITION Then
lRange = lRange * lMaxOccurence
If lMaxOccurence < 1 Then
UniqRandInt = CVErr(xlErrNum)
Exit Function
End If
#Else
If lMaxOccurence < 1 Then
UniqRandInt = CVErr(xlErrNum)
Exit Function
End If
#End If

If Application.Caller.Count lRange Then
UniqRandInt = CVErr(xlErrValue)
Exit Function
End If

ReDim vR(1 To Application.Caller.Rows.Count, _
1 To Application.Caller.Columns.Count)

ReDim vA(1 To lRange)
#If Not LATE_INITIALISATION Then
For i = 1 To lRange
#If ALLOW_REPETITION Then
vA(i) = Int((i - 1) / lMaxOccurence) + 1
#Else
vA(i) = i
#End If
Next i
#End If

i = 1
For lRow = 1 To UBound(vR, 1)
For lCol = 1 To UBound(vR, 2)
lr = Int(((lRange - i + 1) * Rnd) + 1)
#If LATE_INITIALISATION Then
If vA(lr) = 0 Then 'Late initialisation
#If ALLOW_REPETITION Then
vR(lRow, lCol) = Int((lr - 1) / lMaxOccurence) + 1
#Else
vR(lRow, lCol) = lr
#End If
Else
#End If
vR(lRow, lCol) = vA(lr)
#If LATE_INITIALISATION Then
End If
If vA(lRange - i + 1) = 0 Then 'Late initialisation
#If ALLOW_REPETITION Then
vA(lr) = Int((lRange - i + 1 - 1) / lMaxOccurence) +
1
#Else
vA(lr) = lRange - i + 1
#End If
Else
#End If
vA(lr) = vA(lRange - i + 1)
#If LATE_INITIALISATION Then
End If
#End If
i = i + 1
Next lCol
Next lRow

UniqRandInt = vR

End Function

HTH, Bernd