PDA

Click to See Complete Forum and Search --> : What's Random about this?


ausmoran
Sep 13th, 2000, 08:13 AM
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

Ianpbaker
Sep 13th, 2000, 09:19 AM
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