Mike
Mike

Reputation: 14586

Add new record to the table by click on the button in Microsoft Access

In my MS Access form I want to implement a separate button, that adds a new record to the table. In order to do that I added a button and attached to this button an event:

Private Sub btnAddRec_Click()
    Refresh
    With CodeContextObject
        On Error Resume Next
        DoCmd.GoToRecord , , acNewRec
        If Err.Number <> 0 Then
            btnAddRec.Enabled = False
        End If
    End With
End Sub

Everything is OK when you just open the window and click the btnAddRec button, the problem is when you first of all perform the navigation through existed records and only after that click on this button. I got the runtime error:

2105: «You can't go to the specified record. You may be at the end of a recordset».

How to solve the issue? I need to have ability to add the new record on click on specific button, no matter, have I walked or not walked through the records before.

Upvotes: 0

Views: 34635

Answers (1)

ron tornambe
ron tornambe

Reputation: 10780

I created a simple form with a field call Description (and AutoNumber) and created a button with the code that follows click event. I filled it with a number of records and navigated through them, then clicked the addNewRec button. The form navigated to the new record without issues. I was also able to click the addNewRec button directly after opening the form successfully.

Private Sub btnAddRec_Click()
On Error GoTo Err1
    DoCmd.GoToRecord , , acNewRec
    Exit Sub
Err1:
    Description.SetFocus
    btnAddRec.Enabled = False
    MsgBox (Err.Description)
End Sub

The differences from the code you included were removing the refresh and With statement, handing the error, setting focus before disabling the button and showing the user the error description. I do not know if your form is similar, but this should work for you if it is and I understood your problem correctly.

Upvotes: 1

Related Questions