Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Return Random Record

Status
Not open for further replies.

ptuck

MIS
Aug 8, 2003
130
US
I need some help returning a random record in Access 2002. I have tried the following solution form Microsoft, but continue to get "Type Mismatch" error on the Set MyRS = MyDB.OpenRecordset(RecordSetName, dbOpenDynaset) line. The goal is to have the program determine a winner from a drawing. Hope you guru's can help.

Function FindRandom(RecordSetName As String, Fieldname As String)

Dim MyDB As Database
Dim MyRS As Recordset
Dim SpecificRecord As Long, i As Long, NumOfRecords As Long

Set MyDB = CurrentDb()
Set MyRS = MyDB.OpenRecordset(RecordSetName, dbOpenDynaset)
On Error GoTo NoRecords
MyRS.MoveLast
NumOfRecords = MyRS.RecordCount
SpecificRecord = Int(NumOfRecords * Rnd)
If SpecificRecord = NumOfRecords Then
SpecificRecord = SpecificRecord - 1
End If
MyRS.MoveFirst
For i = 1 To SpecificRecord
MyRS.MoveNext
Next i
FindRandom = MyRS(Fieldname)
Exit Function

NoRecords:
If Err = 3021 Then
MsgBox "There Are No Records In The Dynaset", 16, "Error"
Else
MsgBox "Error - " & Err & Chr$(13) & Chr$(10) & Error, _
16, "Error"
End If
FindRandom = "No Records"
Exit Function

End Function

Thanks,
Paul
 
Make the folloiwng red code modifications:

Code:
Dim MyDB As [RED]DAO.[/RED]Database
Dim MyRS As [RED]DAO.[/RED]Recordset

Post back if you have any other questions.

[COLOR=006633]Bob Scriver[/color]
MIState1.gif
[COLOR=white 006633]MSU Spartan[/color]
 
I am having problems calling the above function that I got from Microsoft. It is working when I test it from the immediate window, but can't call it. What I want to do is set a form or report to have the record source of the record it pulls.

Please help,
Paul
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top