Sub Random()
Dim SCA, i, r, k, s, LO_P, LO_HA, Arr, Arr_P, Arr_HA, Res
t = Timer
Set SCA = CreateObject("system.collections.arraylist")
Set LO_P = Sheets("Blad1").ListObjects("TBL_Players") '
Arr_P = LO_P.DataBodyRange
col2 = LO_P.DataBodyRange.Columns(2)
ReDim Res(1 To UBound(Arr_P), 1 To 1)
Arr = Sheets("Blad1").ListObjects("Hole_Assigment").DataBodyRange
Arr_HA = Arr
col1 = Application.Index(Arr, 0, 1) '1st column = cards
ReDim Preserve Arr_HA(1 To UBound(Arr), 1 To UBound(Arr, 2) + 1)
For i = 1 To UBound(Arr_P) 'all the players with a pre-assigned card
If Len(Arr_P(i, 1)) > 0 Then
r = Application.Match(Arr_P(i, 1), col1, 0) 'find card in 1st col
If IsNumeric(r) Then
Arr_HA(r, UBound(Arr_HA, 2)) = Arr_HA(r, UBound(Arr_HA, 2)) + 1 'increment number of players with that card
Res(i, 1) = Arr_P(i, 1) 'assign player to that card
Else
MsgBox "card not found, ERROR"
Res(i, 1) = "????" 'assign player to card "???"
End If
Else
SCA.Add Arr_P(i, 2) 'arraylist of FREE players
End If
Next
Do While SCA.Count 'as long as there are FREE players
b = False
i = WorksheetFunction.RandBetween(1, SCA.Count) 'take a random still Free player
s = SCA.Item(i - 1)
Arr = Evaluate("column(A1:Z1)") 'serie 1 to 26 (> number of cards
For j = UBound(Arr_HA) To 1 Step -1 'choice a random card
k = WorksheetFunction.RandBetween(1, j) 'take a random Free player
l = Arr(k)
If Arr_HA(l, UBound(Arr_HA, 2)) >= Range("Card_Size").Value Then
Arr(k) = Arr(j)
Else
r = Application.Match(SCA.Item(i - 1), col2, 0)
If IsNumeric(r) Then Res(r, 1) = Arr_HA(l, 1)
Arr_HA(l, UBound(Arr_HA, 2)) = Arr_HA(l, UBound(Arr_HA, 2)) + 1 'increment number of players with that card
SCA.Remove SCA.Item(i - 1)
b = True
Exit For
End If
Next
If Not b Then
SCA.Remove SCA.Item(i - 1)
End If
Loop
LO_P.ListColumns("Group").DataBodyRange.Value = Res
'MsgBox Timer - t
End Sub