VBA code example that creates a new table in a Microsoft Access database


 Sub CreateTable()

    Dim db As DAO.Database

    Set db = CurrentDb

    Dim tbl As DAO.TableDef

    Set tbl = db.CreateTableDef("MyTable")

    

    'Add fields to the table'

    Dim fld1 As DAO.Field

    Set fld1 = tbl.CreateField("ID", dbLong)

    fld1.Attributes = dbAutoIncrField

    tbl.Fields.Append fld1

    

    Dim fld2 As DAO.Field

    Set fld2 = tbl.CreateField("Name", dbText, 50)

    tbl.Fields.Append fld2

    

    Dim fld3 As DAO.Field

    Set fld3 = tbl.CreateField("Age", dbInteger)

    tbl.Fields.Append fld3

    

    'Save the table definition'

    db.TableDefs.Append tbl

    db.TableDefs.Refresh

    Set tbl = Nothing

    Set db = Nothing

End Sub



This code creates a new table called "MyTable" with three fields: "ID", "Name", and "Age". The "ID" field is set to be an auto-incrementing field, and the other two fields are set to be of type "Text" and "Integer", respectively.

You can modify this code to add more fields or change the field types as per your requirements.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.