The following sample function will return a random record using the
recordset name and the field name that you provide.
NOTE: The sample code in this article uses Microsoft Data Access Objects. For this code to run properly, you must reference the Microsoft DAO 3.6 Object Library. To do so, click
References on the
Tools menu in the Visual Basic Editor, and make sure that the
Microsoft DAO 3.6 Object Library check box is selected.
Create a module and type the following line in the Declarations section
if it is not already there:
Type the following procedure:
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
To test this function, type the following line in the Immediate window, and then press ENTER:
?FindRandom("<RecordSetName>", "<FieldName>")
where <RecordSetName> is the name of a table or query or a SQL statement and <FieldName> is the name of a field in your recordset.
Note that each time that you run the function, a different record is
returned.