View Single Post
 
Old 02-23-2012, 06:31 AM
tinfanide tinfanide is offline Windows 7 64bit Office 2010 32bit
Expert
 
Join Date: Aug 2011
Posts: 312
tinfanide is on a distinguished road
Default How to reserve an array in a public function?

Code:
Sub test()

Dim x As Integer

For x = 0 To 3
    MsgBox (ReturnRandomNumber(0, 3, x))
Next x

End Sub

Public Function ReturnRandomNumber(lower As Integer, upper As Integer, turn As Integer) As String
    
    Dim n As Integer, arr() As Variant
    
Redo:
    n = Int((upper - lower + 1) * Rnd + lower)
    
    ReDim Preserve arr(turn)
    
    ''' I want to store every n to check if the random number generated is repeated
    For Each a In arr
        If a = n Then GoTo Redo
    Next a
    
    ''' Within this function, the Array arr() does not store every n
    arr(turn) = n
    ReturnRandomNumber = n
    
End Function
If I move the foreach loop and the array within the sub, it can loop through the array and check if the newly generated random number is repeated.

But it does not work within a public function.
Reply With Quote