Access - saving data

Asked

Viewed 54 times

1

I have the VBA code below that saves a new release. When Close the Form, even if I have entered any name, it is not saved. But I noticed that Access automatically generates a new primary key, ie skips a primary key that will no longer be used. Example: if I had until primary key 9, when closing the form Access will skip primary key 10, and when opening the form again the next primary key will be 11. It’s normal or it’s avoidable?

Option Compare Database

Private Sub Form_Load()
    DoCmd.GoToRecord , , acNewRec
    Me.NomeGrupo.SetFocus
End Sub


Private Sub btSalvar_Click()
    Me.NomeGrupo.SetFocus
    If Me.NomeGrupo.Text = Empty Then
        MsgBox "Operação cancelada!" & vbNewLine & vbNewLine & _
        "O campo Nome do grupo está vazio!", vbInformation, " CADASTRO DE GRUPOS"
        Exit Sub
    End If
    If (Not IsNull(DLookup("[NomeGrupo]", "tabGrupos", "[NomeGrupo] ='" & Me!NomeGrupo & "'"))) Then
        MsgBox "Operação cancelada!" & vbNewLine & vbNewLine & _
        "O grupo " & Me.NomeGrupo.Text & " já está cadastrado no sistema!", vbInformation, "CADASTRO DE GRUPO"
        Cancel = True 'cancela o evento.
        Me!NomeGrupo.Undo 'desfaz a digitação.
    Else
        DoCmd.GoToRecord , , acNewRec
        MsgBox "Cadastro realizado com sucesso!", vbInformation, " CADASTRO DE GRUPOS"
    End If

End Sub

Private Sub btFechar_Click()
    Me.Undo
    DoCmd.Close acForm, "FormGrupos"
End Sub

1 answer

-1

When nothing is done in the form the entry is not inserted in the table. But, if you edit a field, undo the edit (with escape p.ex) and reopen, a new key appears, being in the table the one not used. If the form was used and discarded, there is no way.

Now, if you just clicked the button to execute the code and even then the ID is renewed then it is because the concept of using the form extended to the code, that is, it is as if the form had been used and undone with a double escape, but I cannot say categorically because I have not tested.

If so, just make your form a form sub-form of the form where the button is, or better yet, (to be tested) pass the Header or Footer button of the form.

  • Me, newbie, giving you trouble. Thanks for the hkotsubo tip!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.