1

I am trying to simulate a multiple deck drawing using an array. After the first card is dealt, how can I remove this random number ("p1") from the deck array, so I can have an array with 51 elements without the first one to be selected?

That`s how I am doing it so far

Dim deck(1 To 52) As Variant
Dim p1 As Integer


For i = 1 To 52

    deck(i) = i

Next

p1 = Int((UBound(deck) * Rnd) + 1)
3
  • Possible duplicate of Remove the first element of a VBA array Commented Oct 21, 2019 at 0:24
  • 1
    My VBA is really rusty, but I think when you create your deck as a Collection instead of an array, you will have easier control over your deck. A collection allows for simple adding and removeing of elements. Commented Oct 21, 2019 at 0:42
  • 1
    Welcome to SO! When you place a question try to add a minimum content: input sample, expected output sample, what did you try, research and where are you stacked. Your question is clear, but what did you try? How are you trying to remove one element? Commented Oct 21, 2019 at 3:32

2 Answers 2

1

I could solve it with the code below but I am still wondering if there is an easier way

Sub preflop()

Dim deck() As Integer
Dim p1 As Integer


For i = 1 To 52
    ReDim Preserve deck(1 To i) As Integer
    deck(i) = i
Next

p1 = Int((UBound(deck) * Rnd) + 1)

For i = LBound(deck) To UBound(deck)
    If deck(i) = p1 Then
        For j = i To UBound(deck) - 1
            deck(j) = deck(j + 1)
        Next
    End If
Next

ReDim Preserve deck(1 To UBound(deck) - 1) As Integer


End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

You can look in either a VBA collection or .NET arraylist. You can delete items per index number from these class objects.
1

As per my comment, here an example on how you can utilize an ArrayList for this purpose:

Sub preflop()

Dim arr As Object: Set arr = CreateObject("System.Collections.ArrayList")
Dim item As Variant, ResultArr As Variant
Dim i As Long, p1 As Long

With arr

    'Load all variables
    For i = 1 To 52
        .Add i
    Next i

    'Get random number
    p1 = ((.Count - 1) - 1) * Rnd

    'Remove the random card from the deck
    .Remove (p1)

    'To use an array in further code somewhere
    ResultArr = .Toarray

End With

End Sub

AFAIK the use of ArrayList over the more native Collection will open ways to use methods like Toarray to export the arrayList to an array without an expensive Redim loop.

If you don't need to end up with an array you might as well use the Collection approach.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.