NewCurrentDatabase Method Example

The following example creates a new Microsoft Access database from another application through Automation, and then creates a new table in that database.

You can enter this code in a Visual Basic module in any application that can act as a COM component. For example, you might run the following code from Microsoft Excel, Microsoft Visual Basic, or Microsoft Access.

When the variable pointing to the Application object goes out of scope, the instance of Microsoft Access that it represents closes as well. Therefore, you should declare this variable at the module level.

' Include following in Declarations section of module.
Dim appAccess As Access.Application

Sub NewAccessDatabase()
    Dim dbs As Object, tdf As Object, fld As Variant
    Dim strDB As String
    Const DB_Text As Long = 10
    Const FldLen As Integer = 40

    ' Initialize string to database path.
    strDB = "C:\My Documents\Newdb.mdb"
    ' Create new instance of Microsoft Access.
    Set appAccess = _
        CreateObject("Access.Application.9")
    ' Open database in Microsoft Access window.
    appAccess.NewCurrentDatabase strDB
    ' Get Database object variable.
    Set dbs = appAccess.CurrentDb
    ' Create new table.
    Set tdf = dbs.CreateTableDef("Contacts")
    ' Create field in new table.
    Set fld = tdf. _
        CreateField("CompanyName", DB_Text, FldLen)
    ' Append Field and TableDef objects.
    tdf.Fields.Append fld
    dbs.TableDefs.Append tdf
    Set appAccess = Nothing
End Sub