Atiq
Atiq

Reputation: 1

Access 2016 codes are inserting duplicate record

I'm new in writing codes behind an Access form. I have written the following codes behind 'New' button:

Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim MyDate As Date

Set db = CurrentDb
Set rst = db.OpenRecordset("SELECT * FROM STOCK_IN ORDER BY RecNo;", dbOpenDynaset)
If rst.BOF And rst.EOF Then
Else
    rst.MoveLast
    MyDate = rst!TDate

End If

DoCmd.GoToRecord , , acNewRec

[TDate] = MyDate

Set rst = Nothing

AdFlag = True

And the following codes behind the 'Save' button:

    If AdFlag = True Then
    Dim db1 As DAO.Database
    Dim rst1 As DAO.Recordset
    Set db1 = CurrentDb
    Set rst1 = db1.OpenRecordset("SELECT * FROM STOCK_IN ORDER BY RecNo;", 
dbOpenDynaset)

    With rst1
        .AddNew
        ![TDate] = TDate
        ![IName] = IName
        ![StockIn] = StockIn
        .Update
        .Close
    End With

    Set rst1 = Nothing
    Me.Requery
    AdFlag = False

End If

But each records are being doubly saved, i.e., I'm getting two same records. Could anyone find me the problem in the codes?

Upvotes: 0

Views: 27

Answers (1)

Erik A
Erik A

Reputation: 32642

If you're using a bound form, you don't need to have a save button at all. Access handles saving for you when you close the form, requery, etc.

Because you're manually saving too, you're saving records twice.

If you want to have a save button anyway (for example, if you want to move to a new record after saving), you only need the following code to save the current record:

Me.Dirty = False

Alternatively, you can use a DoCmd statement:

DoCmd.RunCommand acCmdSaveRecord

Upvotes: 2

Related Questions