CreateField Method Example (MDB)

The following example creates a new table with two new fields. One of the fields is an AutoNumber field. The procedure also makes this field the primary key in the table.

Sub NewTable()
    Dim dbs As Database
    Dim tdf As TableDef, fld1 As Field, fld2 As Field
    Dim idx As Index, fldIndex As Field

    ' Return reference to current database.
    Set dbs = CurrentDb
    ' Create new table with two fields.
    Set tdf = dbs.CreateTableDef("Contacts")
    Set fld1 = tdf.CreateField("ContactID", dbLong)
    fld1.Attributes = fld1.Attributes + dbAutoIncrField
    Set fld2 = tdf.CreateField("ContactName", dbText, 50)
    ' Append fields.
    tdf.Fields.Append fld1
    tdf.Fields.Append fld2
    ' Create primary key index.
    Set idx = tdf.CreateIndex("PrimaryKey")
    Set fldIndex = idx.CreateField("ContactID", dbLong)
    ' Append index fields.
    idx.Fields.Append fldIndex
    ' Set Primary property.
    idx.Primary = True
    ' Append index.
    tdf.Indexes.Append idx
    ' Append TableDef object.
    dbs.TableDefs.Append tdf
    dbs.TableDefs.Refresh
    Set dbs = Nothing
End Sub