Database Object, Databases Collection Example (MDB)

The following example shows three ways to return a Database object in Microsoft Access. The procedure returns a Database object representing the current database, which is open in the Microsoft Access window. Next, the procedure creates another database called Newdb.mdb and saves it to disk. Then it opens an existing database called Another.mdb. Finally, it enumerates all Database objects in the Databases collection.

Sub ReferenceDatabases()
    Dim wsp As Workspace
    Dim dbsCurrent As Database, dbsNew As Database
    Dim dbsAnother As Database, dbs As Database

    ' Return reference to current database.
    Set dbsCurrent = CurrentDb
    ' Return reference to default workspace.
    Set wsp = DBEngine.Workspaces(0)
    ' Create new Database object.
    Set dbsNew = wsp.CreateDatabase("Newdb.mdb", dbLangGeneral)
    ' Open database other than current database.
    Set dbsAnother = wsp.OpenDatabase("Another.mdb")
    ' Enumerate all open databases.
    For Each dbs in wsp.Databases
        Debug.Print dbs.Name
    Next dbs
    For Each dbs In wsp.Databases
        Set dbs = Nothing
    Next dbs
    Set wsp = Nothing
End Sub