Create a form command button that moves the form to a random record

  • Thread starter Thread starter John S. Ford, MD
  • Start date Start date
J

John S. Ford, MD

I have a form bound to an underlying table. Can someone suggest some code
for a command button that would move the form to a random record? I assume
the button's event handler will have some DAO code in it.

Thanks in advance!

John
 
John S. Ford said:
I have a form bound to an underlying table. Can someone suggest some
code for a command button that would move the form to a random record?
I assume the button's event handler will have some DAO code in it.

Try something like this:

Private Sub cmdRandom_Click()
Dim rs As DAO.Recordset
Dim lngHowMany As Long

Randomize
If Me.Dirty Then Me.Dirty = False
Set rs = Me.RecordsetClone
If rs.RecordCount > 0 Then
rs.MoveLast
Me.Bookmark = rs.Bookmark
lngHowMany = Int(rs.RecordCount * Rnd()) + 1
DoCmd.GoToRecord , Me.Name, acPrevious, lngHowMany
End If
Set rs = Nothing
End Sub
 
Thanks Allen. That looks good.

John

Allen Browne said:
Try something like this:

Private Sub cmdRandom_Click()
Dim rs As DAO.Recordset
Dim lngHowMany As Long
Randomize
If Me.Dirty Then Me.Dirty = False
Set rs = Me.RecordsetClone
If rs.RecordCount > 0 Then
rs.MoveLast
Me.Bookmark = rs.Bookmark
lngHowMany = Int(rs.RecordCount * Rnd()) + 1
DoCmd.GoToRecord , Me.Name, acPrevious, lngHowMany
End If
Set rs = Nothing
End Sub
 
Back
Top