Search code examples
randomvb6

Randomize Function in VB6


I have been trying to generate a Random number between 0-3 Multiple times everytime I run a program. I'm using the following code as now:

Private Sub scatterfun()
Dim cout As Integer, temvar As Integer
While (cout < 500)
    Randomize
    temvar = CInt(Int((3 * Rnd(1)) + 0))
    If temvr = 0 Then
        Statements
    ElseIf temvar = 1 Then
         Statements
    ElseIf temvar = 2 Then
         Statements
    ElseIf temvar = 3 Then
        Statements
    End If
    cout = cout + 1
Wend  End Sub

But every time i run it, it shows me the same random number generation pattern. How to generate a set of different random numbers everytime?

I can't get how to use Randomizer()


Solution

  • Your code can be simplified (and corrected; yours only gives from 0 to 2) to this:

    Dim i As Integer
    For i = 0 To 500
        Select Case Int(4 * Rnd())
            Case 0
                Debug.Print "0";
            Case 1
                Debug.Print "1";
            Case 2
                Debug.Print "2";
            Case 3
                Debug.Print "3";
        End Select
    Next
    

    Try it and see. The Randomize statement only sets the seed to the system timer, and Rnd(1) is equivalent to Rnd(). Also, here's the doc on the Rnd function.