Here's a tidbit I figured out today, how to select a random record from table in Microsoft Access 2007. If you don't know how to create a function in Microsoft Access 2007, see
Creating Custom Access Functions.
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.
Sphere: Related Content