Select a Random Record from a Microsoft Access 2007 Table
Assume "MyTable" is the table from which you want to select a record, and that the table has a identifier field, "ID", which is a number that is unique, but not necessarily sequential. Here is the code for a function which returns the identifier for a random row in the table:
Public Function RandomRow() As Integer
'Get access to the database
Dim db As DAO.Database
Set db = CurrentDb()
'Get access to the table
Dim tdf As DAO.TableDef
Set tdf = db.TableDefs("MyTable")
'Get the number of records in the table
Dim total As Integer
total = tdf.RecordCount
'Get the records in the table
Dim rst As DAO.Recordset
Set rst = tdf.OpenRecordset
'Select a random record in the table
Dim randomRecord As Integer
randomRecord = Int(Rnd() * total)+1
'Move to the random record
Dim currentRecord As Integer
currentRecord = 1
rst.MoveFirst
Do While (currentRecord <> randomRecord)
currentRecord = currentRecord + 1
rst.MoveNext
Loop
'Return the unique identifier of the random record
Dim recordID as Integer
recordID = rst.Fields("ID").Value
'Clean up pointers
Set rst = Nothing
Set tdf = Nothing
Set db = Nothing
'Return value
RandomRow = recordID
End Function
I found another solution for this at VBA Tips, but my solution is simpler, not requiring the creation of a temporary table.





Stumble It!
