Next Button that cycles back to first on Access Fo

2019-07-25 18:08发布

问题:

I've been trying a couple things to create a button that navigates back to the first record you are at the last record. I get the "can't go to specified record" error. Here are the two styles of code I have tried for this button:

Private Sub Command161_Click()
    On Error Resume Next
    If Me.CurrentRecord = acLast Then
            DoCmd.GoToRecord , , acFirst
        Else
            DoCmd.GoToRecord , , acNext
       End If

End Sub

Private Sub Command161_Click()
With Me.Recordset
  If .AbsolutePosition = .RecordCount - 1 Then
      DoCmd.GoToRecord , , acFirst
  Else
    DoCmd.GoToRecord , , acNext
  End If
End With

End Sub

The goal is to loop back around to the first record without allowing the user to create a new record. I've tried this code with "allow additions" set to both yes and now, with the same result. Any help would be appreciated.

回答1:

I would suggest defining a private predicate function within your form module which returns a boolean value depending on whether or not the active form is displaying the last record in its Record Source.

Such a function might be written:

Private Function LastRecordP() As Boolean
    With Me.RecordsetClone
        If Not .EOF Then
            .MoveLast
            .MoveFirst
            LastRecordP = Me.CurrentRecord = .RecordCount
        End If
    End With
End Function

Your OnClick event handler for your button control could then be written more succinctly as:

Private Sub Command161_Click()
    If LastRecordP Then
        DoCmd.GoToRecord , , acFirst
    Else
        DoCmd.GoToRecord , , acNext
    End If
End Sub

Alternatively, you could allow the function to accept a Form object as an argument and evaluate such function using the Me keyword, e.g.:

Private Function LastRecordP(Frm As Form) As Boolean
    With Frm.RecordsetClone
        If Not .EOF Then
            .MoveLast
            .MoveFirst
            LastRecordP = Frm.CurrentRecord = .RecordCount
        End If
    End With
End Function
Private Sub Command20_Click()
    If LastRecordP(Me) Then
        DoCmd.GoToRecord , , acFirst
    Else
        DoCmd.GoToRecord , , acNext
    End If
End Sub