Dynamically Create Databases (.MDB’s) in code

By | 2002-06-01

This code creates a Microsoft Access MDB dynamically.

Original Author: Kenny Sendel

Assumptions

This sample code will create a database in the temp directory with the following fields:
fldForeName
fldSurname
fldDOB
fldFurtherDetails

API Declarations

NONE

Code

''
'' PUT THIS BEHIND A COMMAND BUTTON TO TEST
''
' Declarations
Dim tdExample      As TableDef
Dim fldForeName     As Field
Dim fldSurname     As Field
Dim fldDOB       As Field
Dim fldFurtherDetails  As Field
Dim dbDatabase     As Database
Dim sNewDBPathAndName  As String
' Set the new database path and name in string (using time:seconds for some randomality
sNewDBPathAndName = "c: empNewDB" & Right$(Time, 2) & ".mdb"
' Create a new .MDB file (empty at creation point!)
Set dbDatabase = CreateDatabase(sNewDBPathAndName, dbLangGeneral, dbEncrypt)
' Create new TableDef (table called 'Example')
Set tdExample = dbDatabase.CreateTableDef("Example")
' Add fields to tdfTitleDetail.
Set fldForeName = tdExample.CreateField("Fore_Name", dbText, 20)
Set fldSurname = tdExample.CreateField("Surname", dbText, 20)
Set fldDOB = tdExample.CreateField("DOB", dbDate)
Set fldFurtherDetails = tdExample.CreateField("Further_Details", dbMemo)
' Append the field objects to the TableDef
tdExample.Fields.Append fldForeName
tdExample.Fields.Append fldSurname
tdExample.Fields.Append fldDOB
tdExample.Fields.Append fldFurtherDetails
' Save TableDef definition by appending it to TableDefs collection.
dbDatabase.TableDefs.Append tdExample
MsgBox "New .MDB Created - '" & sNewDBPathAndName & "'", vbInformation
' Now look for the new .MDB using File Manager!

Author: dwirch

Derek Wirch is a seasoned IT professional with an impressive career dating back to 1986. He brings a wealth of knowledge and hands-on experience that is invaluable to those embarking on their journey in the tech industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.