I got from VBA Express : Excel - Function to return random sample, with or without replacement the following function:
' Function looks at specified range (Source argument) and returns an array of randomly-
' sampled data from that range. Take argument specifies the number of items in the sample
' Optional argument Replacing indicates whether sampling is done with replacement (i.e.,
' any item in the source may be selected more than once, indicated by True) or without
' replacement (any given item may only be selected once, indicated by False)
' Optional argument Unique indicates whether the samples are drawn from all items in the
' Source range (False), or just from the unique elements (True)
This site also provides the macro below to elaborate game fixtures:
Private Sub Tourney()
Dim arr As Variant
Dim Counter As Long
[d2:e32].ClearContents
arr = Sample([a2:a33], 32)
For Counter = 1 To 16
Cells(Counter * 2, 4) = arr((Counter * 2) - 1)
Cells(Counter * 2, 5) = arr(Counter * 2)
Next
MsgBox "Done"
End Sub
I am trying to make a function that makes the same operation, but I am getting the ByRef type error when computing the function Sample.
Function MYxlTourney(n As Integer)
Dim i As Long
Dim arr As Variant
Dim Player() As Variant
With WorksheetFunction
ReDim Player(1 To n)
For i = 1 To n
Player(i) = "Player " & i
Next i
arr = Sample(Player, 2) ' Error here
MYxlTourney = arr
End With
End Function
Function Sample(Source As Range, Take As Long, Optional Replacing As Boolean = False, Optional Unique As Boolean = False)
' Function by Patrick Matthews' Function looks at specified range (Source argument) and returns an array of randomly-
' sampled data from that range. Take argument specifies the number of items in the sample
' Optional argument Replacing indicates whether sampling is done with replacement (i.e.,
' any item in the source may be selected more than once, indicated by True) or without
' replacement (any given item may only be selected once, indicated by False)
' Optional argument Unique indicates whether the samples are drawn from all items in the
' Source range (False), or just from the unique elements (True)
This site also provides the macro below to elaborate game fixtures:
Private Sub Tourney()
Dim arr As Variant
Dim Counter As Long
[d2:e32].ClearContents
arr = Sample([a2:a33], 32)
For Counter = 1 To 16
Cells(Counter * 2, 4) = arr((Counter * 2) - 1)
Cells(Counter * 2, 5) = arr(Counter * 2)
Next
MsgBox "Done"
End Sub
I am trying to make a function that makes the same operation, but I am getting the ByRef type error when computing the function Sample.
Function MYxlTourney(n As Integer)
Dim i As Long
Dim arr As Variant
Dim Player() As Variant
With WorksheetFunction
ReDim Player(1 To n)
For i = 1 To n
Player(i) = "Player " & i
Next i
arr = Sample(Player, 2) ' Error here
MYxlTourney = arr
End With
End Function