MS Access: Create Autonumber ID field through VBA script

The below script will create autonumber field with name 'ID' after execution.

STEPS:
  1. Create a new form and add a button to it.
  2. Right click on the button, click Build Event and paste below script. Save the form and close.
  3. Open the form and click on the button to create Auto number column.
Private Sub Command1_Click()

Dim DB As Database
Set DB = CurrentDb


Dim tdf As DAO.TableDef
  Dim fld As DAO.Field
  Dim idx As DAO.Index
 
  Set DB = CurrentDb
  Set tdf = DB.TableDefs("Mytable")
 
  With tdf
    ' Append AutoNumberField
    Set fld = .CreateField("ID", dbLong)
    fld.Attributes = .Attributes Or dbAutoIncrField
    .Fields.Append fld
    .Fields.Refresh
   
    ' Set RecordID as PK
    Set idx = .CreateIndex("PK_Table1")
    idx.Fields.Append idx.CreateField("ID")
    idx.Primary = True
    .Indexes.Append idx
   
  End With
 
  Application.RefreshDatabaseWindow

  MsgBox "Autonumber ID column created"
 
End Sub

No comments:

Post a Comment