Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Create a new database using VBA code

How To

Create a new database using VBA code

by  randysmid  Posted    (Edited  )
Hello everyone!

Here is a link to the MSDN page that shows how to accomplish this task within VBA code. It uses the "CreateDatabase" method.
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/off2000/html/acmthCreateDatabaseX.asp

The sample also shows how to create a new table with two fields. In addition, it creates a primary key index.

In case you are unable to access the Microsoft tip, here is the code that they provided:

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

Set wspDefault = DBEngine.Workspaces(0)
' Create new, encrypted database.
Set dbs = wspDefault.CreateDatabase("Newdb.mdb", _
dbLangGeneral, dbEncrypt)
' 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


Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top