MS Access how to Update current row, move to next

2019-07-17 10:19发布

问题:

I have a continuous form with a command button in the footer that updates the current record with a value that will make the record no longer show in the form once requeried. I want the user to be able to click the button and once the record is updated, move to the next record, not the first as is the default behaviour. I have code that I would think should work but doesn't, it keeps going back to the first record on the form.

Private Sub cmdCloseReq_Click()

Dim ReqID As String
ReqID = Me.txtReqID
Dim rst As Recordset
Dim strBookmark As Integer

Set rst = Me.RecordsetClone
rst.MoveNext
If Not rst.EOF Then                 ' if not end-of-file
  strBookmark = rst.Bookmark      ' ...save the next record's bookmark
  Dim cmd As New ADODB.Command
  With cmd
    .ActiveConnection = CurrentProject.Connection
    .CommandType = adCmdStoredProc
    .CommandText = "spUpdateLOG_ReqCompleteDate"
    .Parameters("@ReqID") = ReqID
    .Execute
  End With                 
Me.Requery
Me.Bookmark = strBookmark

End If
Set rst = Nothing   

End Sub

OK, I found a solution based on rene's post. I grab the next records primary key, do an update then after the requesry I find the next record and set the bookmark to that. Here is the code:

Private Sub cmdCloseReq_Click()

Dim ReqID As String
ReqID = Me.txtReqID
Dim rst As New ADODB.Recordset
Dim strBookmark As String

Set rst = Me.RecordsetClone

With rst
 .Find "[ReqID] = '" & ReqID & "'"
 .MoveNext
 strBookmark = rst.Fields(0)

End With

If Not rst.EOF Then                 ' if not end-of-file
      ' ...save the next record's bookmark

  Dim cmd As New ADODB.Command

  With cmd
    .ActiveConnection = CurrentProject.Connection
    .CommandType = adCmdStoredProc
    .CommandText = "spUpdateLOG_ReqCompleteDate"
    .Parameters("@ReqID") = ReqID
    .Execute
  End With                 ' ...delete the record

  Me.Requery

 Set rst = Me.RecordsetClone
 With rst
      .Find "[reqID]= " & strBookmark
    Me.Bookmark = .Bookmark

End With

Else
  With cmd
    .ActiveConnection = CurrentProject.Connection
    .CommandType = adCmdStoredProc
    .CommandText = "spUpdateLOG_ReqCompleteDate"
    .Parameters("@ReqID") = ReqID
    .Execute
  End With                 ' ...delete the record
Me.Requery

End If
Set rst = Nothing 

回答1:

I recall that Bookmarks are invalidated after a Requery. If you have a primary key you can better grab that one and after requery move the current record to the previously obtained primary key