通过 DAO 记录集返回随机记录Return a random record from a DAO Recordset
Access 没有用于从一组记录返回随机记录的内置机制。Access does not have a built-in mechanism for returning a random record from a set of records. 本主题介绍一个用户定义的示例函数,您可以使用该函数返回一个随机记录。This topic describes a sample user-defined function that you can use to return a random record.
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
支持和反馈Support and feedback
有关于 Office VBA 或本文档的疑问或反馈?Have questions or feedback about Office VBA or this documentation? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.