Create Table in a Database

This code shows you how to create a table and it's indexes in a database at run time.

Private Sub Command1_Click()
Dim MyDatabase As Database
Dim NewTable As TableDef
Dim MyArtist As dao.Index
Dim MyIndex2 As dao.Index
Dim MyIndex3 As dao.Index

' open database
Set MyDatabase = OpenDatabase(App.Path + "\mp3Base.mdb")
'create the table
Set NewTable = MyDatabase.CreateTableDef("mp3New")
On Error Resume Next
'delete the table if it already exists
MyDatabase.TableDefs.Delete NewTable.Name

'add the fields in the table, those used below are just an example
With NewTable
  .Fields.Append .CreateField("Title", dbText, 30)
  .Fields.Append .CreateField("Artist", dbText, 30)
  .Fields.Append .CreateField("Album", dbText, 30)
  .Fields.Append .CreateField("Year", dbText, 4)
  .Fields.Append .CreateField("Comment", dbText, 30)
  .Fields.Append .CreateField("Genre", dbText, 1)
  .Fields.Append .CreateField("Position", dbText, 10)
End With

'add indexes in the table
Set MyArtist = NewTable.CreateIndex("Artist")
MyArtist.Fields.Append MyArtist.CreateField("Artist")
NewTable.Indexes.Append MyArtist
Set MyIndex2 = NewTable.CreateIndex("Title")
MyIndex2.Fields.Append MyIndex2.CreateField("Title")
NewTable.Indexes.Append MyIndex2
Set MyIndex3 = NewTable.CreateIndex("Position")
MyIndex3.Fields.Append MyIndex3.CreateField("Position")
NewTable.Indexes.Append MyIndex3

MyDatabase.TableDefs.Append NewTable

'close database
End Sub

You might also like...


 amoibade I am currently (2006) 21 years old, and i am programming since i was 13 (1998)... Now i am studing Mathematics in Auth (Aristotelio University of THessaloniki).


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“PHP is a minor evil perpetrated and created by incompetent amateurs, whereas Perl is a great and insidious evil perpetrated by skilled but perverted professionals.” - Jon Ribbens