Results 1 to 2 of 2

Thread: What's Random about this?

  1. #1

    Thread Starter
    Member
    Join Date
    May 2000
    Location
    NE United States
    Posts
    62

    Question

    In my continuing effort to generate a random record, I am intrigued as to why the following code continues to select the same record from the database (despite the use of the RND function). If you can shed any light on this, I would appreciate it. Thanks in advance!

    Private Sub cmdAddNew_Click()
    Dim SpecificRecord As Long, i As Long, NumOfRecords As Long
    Dim b As Integer
    datCustomers.Recordset.MoveLast
    NumOfRecords = datCustomers.Recordset.RecordCount
    SpecificRecord = Int(NumOfRecords * Rnd)
    If SpecificRecord = NumOfRecords Then
    SpecificRecord = SpecificRecord - 1
    End If
    datCustomers.Recordset.MoveFirst
    For i = 1 To SpecificRecord
    datCustomers.Recordset.MoveNext
    Cls
    Next i
    End Sub

    Does it ever get any easier?

  2. #2
    Fanatic Member Ianpbaker's Avatar
    Join Date
    Mar 2000
    Location
    Hastings
    Posts
    696
    Hi ausmoran

    The reason you get the same recordset is For any given initial seed, the same number sequence is generated because each successive call to the Rnd function uses the previous number as a seed for the next number in the sequence. To get around this problem use the following


    Private Sub cmdAddNew_Click()
    Dim SpecificRecord As Long, i As Long, NumOfRecords As Long
    Dim b As Integer
    datCustomers.Recordset.MoveLast
    NumOfRecords = datCustomers.Recordset.RecordCount

    Randomize
    SpecificRecord = Int(NumOfRecords * Rnd)
    If SpecificRecord = NumOfRecords Then
    SpecificRecord = SpecificRecord - 1
    End If
    datCustomers.Recordset.MoveFirst
    For i = 1 To SpecificRecord
    datCustomers.Recordset.MoveNext
    Cls
    Next i
    End Sub

    Randomize uses number to initialize the Rnd function's random-number generator, giving it a new seed value. If you omit number, the value returned by the system timer is used as the new seed value.

    Hope this helps

    Ian

    Yeah, well I'm gonna build my own lunar space lander! With blackjack aaaaannd Hookers! Actually, forget the space lander, and the blackjack. Ahhhh forget the whole thing!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width