I developed a simple deck shuffle and drawing system, as a test on how to use collections and learn from it.
However, I think my code is a bit wonky, and I think here is the best place to get new tips on what to improve.
Public deck As New Collection Public face As New Collection Public symbols As New Collection Sub atomic() face.Add "A" For i = 2 To 10 face.Add i Next i face.Add "J" face.Add "Q" face.Add "K" symbols.Add ChrW(9826) symbols.Add ChrW(9828) symbols.Add ChrW(9825) symbols.Add ChrW(9831) End Sub Sub lime() Set deck = Nothing Set face = Nothing Set symbols = Nothing Dim i As Long For i = 1 To 52 deck.Add i Next i atomic End Sub Sub versive(draw As Long) Dim randc As Long Dim ub As Long Dim cardnumber As Long Dim actualcard As String Dim actualcard2 As String Dim i As Long Dim lastrow As Long lastrow = Cells(Rows.count, 14).End(xlUp).row For i = 1 To draw ub = deck.count If ub = 0 Then MsgBox "Out of cards" Exit Sub End If randc = Int((ub - 1 + 1) * Rnd() + 1) If randc > ub Then randc = ub End If cardnumber = deck.Item(randc) deck.Remove (randc) actualcard = face.Item(cardnumber - (WorksheetFunction.RoundUp(cardnumber / 13, 0) - 1) * 13) & symbols.Item(WorksheetFunction.RoundUp(cardnumber / 13, 0)) lastrow = lastrow + 1 Cells(lastrow, 14).Value = actualcard Next i End Sub Private Sub CommandButton1_Click() versive (51) End Sub Private Sub CommandButton2_Click() lime End Sub
If it matters, it is developed on Excel VBA.
atomic sub calls for the definition of the cards names, because it was not just numbers (Like 1 is actually "A") and the definition for the symbols (Hearts, diamonds, etc).
lime sub basically restarts everything. It runs the
atomic sub, so
lime actually needs to run first. It also defines that the
deck will have 52 cards.
versive sub actually draws cards. So after it gets a random number from 1 to the amount of cards left in the
deck, it converts the number to the actual value and symbols of cards, doing some math to convert it in such a way that number 1 becomes Ace of Diamonds and number 52 becomes King of Clubs.
Versive sub also allows multiple cards drawn at once.