Seven years later, I don't see how to do this in DAO in any of the answers above or anywhere else on any Stack Exchange site. So here is the method I've worked out. The following VBA code creates a table with an autonumber field as primary key, puts some arbitrary data in it, then opens the table to show the results. I've run this code successfully in Access 2007.
Sub Make_Table_With_Autonum_Using_DAO()
Dim oDB As DAO.Database: Set oDB = CurrentDb()
Dim oTable As DAO.TableDef, sObjTable As String: sObjTable = "table_name"
Dim oField As DAO.Field, oIndex As DAO.Index
Dim oRS As DAO.Recordset
Set oTable = oDB.CreateTableDef(sObjTable)
With oTable
Set oField = .CreateField("ID_Object", dbLong) ' Create ID field.
oField.Attributes = dbAutoIncrField ' Make it autoincrement.
.Fields.Append oField ' Add to table's Fields collection.
Set oIndex = .CreateIndex("Index_Object") ' Create index.
oIndex.Primary = True ' Make it a primary key.
Set oField = oIndex.CreateField("ID_Object") ' Make index field for ID field.
oIndex.Fields.Append oField ' Add it to index's Fields coll'n.
.Indexes.Append oIndex ' Add index to table's Indexes coll'n.
Set oIndex = Nothing ' Remove index from memory.
Set oField = Nothing ' Remove field from memory.
.Fields.Append .CreateField("field2", dbText) ' Create and add other fields to
.Fields.Append .CreateField("field3", dbInteger) ' table's Fields collection.
' etc.
End With
oDB.TableDefs.Append oTable ' Add table to database's TableDefs collection.
Set oTable = Nothing
Set oRS = oDB.OpenRecordset(sObjTable) ' Enter arbitrary data into table.
oRS.AddNew: oRS!Field2 = "text 1": oRS!field3 = 123: oRS.Update
oRS.AddNew: oRS!Field2 = "text 2": oRS!field3 = 456: oRS.Update
oRS.AddNew: oRS!Field2 = "text 3": oRS!field3 = 789: oRS.Update
oRS.Close
DoCmd.OpenTable (sObjTable)
oDB.Close
Set oRS = Nothing
Set oDB = Nothing
End Sub
The Microsoft documentation for the necessary VBA elements, in order of appearance in the code, is:
That documentation says everything that needs to be known, but doesn't put it all together to explain how to make the autonumber primary key. The following MS documentation (no longer available directly from MS) does explain how to make the autonumber field, but not how to make it the primary key.
In the following post on a Microsoft community forum, the accepted answer by Andrey Artemyev explains the whole thing.
My code above is essentially the same as his in that answer, with some additional commentary to explain what's going on.