This is Part 1 of 7 in a tutorial on using code to integrate Excel and Access.
In the sample file, Population projections has actual populations by country for 1950 and 2000, with forecasts going out to 2050. By clicking the Create Database button, you will create an Access database called Populations.mdb in the same folder as the Excel file. It contains a single table, tblPopulation, with seven fields. This database will be used for the remainder of the tutorial, so creating it is the first step in the process.
Note:
The constant is shown below. It needs to go before the first Sub procedure in the module:
Const TARGET_DB = "DB_test1.mdb"
Now for the first procedure, which runs when you click Create Database on the Population Projections sheet:
Sub CreateDB_And_Table()
Dim cat As ADOX.Catalog
Dim tbl As ADOX.Table
Dim sDB_Path As String
sDB_Path = ActiveWorkbook.Path & Application.PathSeparator & TARGET_DB
'delete the DB if it already exists
On Error Resume Next
Kill sDB_Path
On Error GoTo 0
'create the new database
Set cat = New ADOX.Catalog
cat.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & sDB_Path & ";"
'create the table
Set tbl = New ADOX.Table
tbl.Name = "tblPopulation"
'create the fields for the new table
tbl.Columns.Append "PopID", adInteger
tbl.Columns.Append "Country", adVarWChar, 60
tbl.Columns.Append "Yr_1950", adDouble
tbl.Columns.Append "Yr_2000", adDouble
tbl.Columns.Append "Yr_2015", adDouble
tbl.Columns.Append "Yr_2025", adDouble
tbl.Columns.Append "Yr_2050", adDouble
'append the newly defined table to the Tables collection in the database
cat.Tables.Append tbl
'Clean up references
Set cat = Nothing
End Sub
Note the order in which this happens.
ADOX is an extension to ADO that lets you create and modify database structures (tables and fields). It was created specifically for working with the Jet database engine. According to Microsoft, you might have problems using it with other database engines.
However, it is useful for creating tables and fields because you can easily define data types and indexes (which you cannot do in ADO).