I needed to append new records to an existing table and have the primary key integer increment automatically. I couldn't find a single command to do it, so I resorted to this:
Set rstTemp = CurrentDb.OpenRecordset("SELECT LAST(ID) FROM tblTable")
avarData = rstTemp.GetRows(1)
CurrentDb.Execute "INSERT INTO tblTable (ID, Field1, Field2, Field3, Field4) VALUES (" & avarData(0, 0) + 1 & ", " & Forms!frmForm.Value1 & ", " & Forms!frmForm.Value2 & ", " & Forms!frmForm.Value3 & ", " & Forms!.frmForm.Value4 & ")"
That seemed to be working okay, and I began entering records with my module, but now suddenly I find that the first two lines of the above code are repeatedly returning an avarData(0, 0) value of 102. It won't go past 102 even if I enter additional records (manually) so the last ID is greater than 102. The INSERT INTO command can't add a new record because it always tries to enter the (already existing) record 102. Why does SELECT LAST(ID) fail to return the ID of the true last record? It doesn't seem to see any records added after the one with ID 102. I don't understand that at all.
But actually I wish I didn't have to actively manage the incrementation of the ID field at all. ID is the primary key field of the table, and an autonumber field, so it seems like it should be able to take care of itself. But INSERT INTO requires values for all fields. Is there an easier approach that I am missing? It seems like this should be simpler.
Set rstTemp = CurrentDb.OpenRecordset("SELECT LAST(ID) FROM tblTable")
avarData = rstTemp.GetRows(1)
CurrentDb.Execute "INSERT INTO tblTable (ID, Field1, Field2, Field3, Field4) VALUES (" & avarData(0, 0) + 1 & ", " & Forms!frmForm.Value1 & ", " & Forms!frmForm.Value2 & ", " & Forms!frmForm.Value3 & ", " & Forms!.frmForm.Value4 & ")"
That seemed to be working okay, and I began entering records with my module, but now suddenly I find that the first two lines of the above code are repeatedly returning an avarData(0, 0) value of 102. It won't go past 102 even if I enter additional records (manually) so the last ID is greater than 102. The INSERT INTO command can't add a new record because it always tries to enter the (already existing) record 102. Why does SELECT LAST(ID) fail to return the ID of the true last record? It doesn't seem to see any records added after the one with ID 102. I don't understand that at all.
But actually I wish I didn't have to actively manage the incrementation of the ID field at all. ID is the primary key field of the table, and an autonumber field, so it seems like it should be able to take care of itself. But INSERT INTO requires values for all fields. Is there an easier approach that I am missing? It seems like this should be simpler.