lundi 11 décembre 2023

Excel VBA Code for lottery and duplicates

I want to make a lottery in Excel where I can draw aprox 30 random numbers between 1-1000 and where the 30 numbers aren't duplicates.

I can't figure out how to check if the Array have duplicates and run the code again if so.

I currently use below VBA code to generate random numbers/winners. I do not think this is the most efficient way but this is what i got... :)

Public Sub CommandButton1_Click()
    Dim MIN, MAX, OUT, i
    Static a, n, z
    MIN = Array(1, 1, 1, 1): MAX = Array(10, 10, 10, 10): OUT = Array("Q1", "Q2", "Q3", "Q4")
    z = UBound(MIN)
    If Not IsArray(n) Then ReDim a(z): ReDim n(z)
    For i = 0 To z
        If n(i) = 0 Then Reset a(i), n(i), MIN(i), MAX(i)
        Range(OUT(i)) = a(i)(n(i)): n(i) = n(i) - 1
    Next
End Sub

Private Sub Reset(a, n, MIN, MAX)
    Dim i, j
    Randomize: n = MAX - MIN + 1: ReDim a(1 To n)
    For i = 1 To n
        j = Rnd * (i - 1) + 1: a(i) = a(j): a(j) = i - 1 + MIN
    Next
End Sub

If you can help me or know of a better way to code this please hmu! :)

Thanks! Oskar




Aucun commentaire:

Enregistrer un commentaire