There are two methods to create an AutoNumber field from code. One requires you
to run a SQL DDL "Create Table" statement, and the other uses
VBA to append dbAutoIncrField flag to a new field's Attributes
property.
To create the field using SQL DDL statements, refer to this Knowledge Base article:
To create the field using VBA and DAO, you can use this function.
Function fCreateAutoNumberField( _
ByVal strTableName As String, _
ByVal strFieldName As String) _
As Boolean
On Error GoTo ErrHandler
Dim db As DAO.Database
Dim fld As DAO.Field
Dim tdf As DAO.TableDef
Set db = Application.CurrentDb
Set tdf = db.TableDefs(strTableName)
Set fld = tdf.CreateField(strFieldName, dbLong)
With fld
.Attributes = .Attributes Or dbAutoIncrField
End With
With tdf.Fields
.Append fld
.Refresh
End With
fCreateAutoNumberField = True
ExitHere:
Set fld = Nothing
Set tdf = Nothing
Set db = Nothing
Exit Function
ErrHandler:
fCreateAutoNumberField = False
With Err
MsgBox "Error " & .Number & vbCrLf & .Description, _
vbOKOnly Or vbCritical, "CreateAutonumberField"
End With
Resume ExitHere
End Function
|