可以使用 CloseCurrentDatabase 方法從另一個通過自動化打開數(shù)據庫的程序中關閉當前數(shù)據庫(Microsoft Access 數(shù)據庫 (.mdb) 或 Access 項目 (.adp))。
expression.CloseCurrentDatabase
expression 必需。返回“應用于”列表中的一個對象的表達式。
例如,可以從 Microsoft Excel 中使用該方法在打開另一個數(shù)據庫之前關閉當前在 Microsoft Access 窗口中打開的數(shù)據庫。
CloseCurrentDatabase 方法用于從另一個程序中通過自動化打開 Microsoft Access 數(shù)據庫時。從另一個程序中打開 Microsoft Access 的實例之后,必須新建一個數(shù)據庫,或指定打開一個現(xiàn)有的數(shù)據庫。該數(shù)據庫將在 Microsoft Access 窗口中打開。
如果使用 CloseCurrentDatabase 方法關閉了在 Microsoft Access 的當前實例中打開的數(shù)據庫,則以后打開其他數(shù)據庫時就不必創(chuàng)建另一個 Microsoft Access 實例。
以下示例通過 Automation 從其他應用程序打開一個 Microsoft Access 數(shù)據庫,在其中創(chuàng)建一個新窗體并保存它,然后關閉該數(shù)據庫。
可以將這段代碼添加到任何能夠作為 COM 組件的應用程序的 Visual Basic 模塊中。例如,可從 Microsoft Excel 或 Microsoft Visual Basic 中運行下面的代碼。
當指向 Application 對象的變量超出范圍時,它所表示的 Microsoft Access 實例也將關閉。所以,必須在模塊級說明這個變量。
' Enter following in Declarations section of module.
Dim appAccess As Access.Application
Sub CreateForm()
Const strConPathToSamples = "C:\Program Files\Microsoft Office\Office11\Samples\"
Dim frm As Form, strDB As String
' Initialize string to database path.
strDB = strConPathToSamples & "Northwind.mdb"
' Create new instance of Microsoft Access.
Set appAccess = CreateObject("Access.Application")
' Open database in Microsoft Access window.
appAccess.OpenCurrentDatabase strDB
' Create new form.
Set frm = appAccess.CreateForm
' Save new form.
appAccess.DoCmd.Save , "NewForm1"
' Close currently open database.
appAccess.CloseCurrentDatabase
Set AppAccess = Nothing
End Sub