注:此回复已自动翻译。因此,它可能包含语法错误或表达尴尬。
你好@何尧
感谢您联系问答论坛。
根据你提供的信息,我理解你的场景是:
在 Solution1.accdb 中通过 VBA 创建 Access.Application 对象,并使用 OpenCurrentDatabase 打开另一个数据库 Base1.accdb。数据库实际上已经被打开(生成了 .laccdb 文件),但 Access 窗口未显示,且即使关闭当前数据库或主数据库,Base1.accdb 仍然被锁定,只能通过任务管理器结束进程才能恢复正常。
结合你提供的代码以及我查阅的资料,这是 Access 自动化(Automation)中的正常行为。
当你使用 CreateObject("Access.Application") 创建 Access 实例时,该实例默认在后台运行,Visible 和 UserControl 属性均为 False。
CloseCurrentDatabase 方法 只会关闭当前数据库,但 不会关闭 Access 应用程序本身,因此 Access 进程仍在后台运行,导致 Base1.accdb 一直被占用和锁定。
要彻底关闭 Base1.accdb 并释放文件锁,必须显式调用 Application.Quit 方法。根据官方文档,只有在调用 Quit 并且释放对象引用后,自动化创建的 Access 实例才会真正退出。
这是为你的 Sub1 修正后的代码:
Private Sub Sub1()
Dim appAccess As Access.Application
On Error GoTo ErrorHandler
Set appAccess = CreateObject("Access.Application")
appAccess.OpenCurrentDatabase "D:\Access_Design\Base1.accdb"
' (Optional: Do something with the opened database here, e.g., run queries)
' Close and quit
appAccess.CloseCurrentDatabase
appAccess.Quit acQuitSaveNone ' Or acQuitSaveAll if you need to save changes
ExitSub:
Set appAccess = Nothing
Exit Sub
ErrorHandler:
MsgBox "Error: " & Err.Description
Resume ExitSub
End Sub
在一个 Access 文件中使用 OpenCurrentDatabase 有效地打开另一个 Access 数据库,并避免数据库被占用或无法关闭时,可以参考以下做法。
首先,创建一个新的 Access 实例,即初始化一个 Access.Application 对象,并使用该实例来打开目标数据库。默认情况下,通过自动化方式创建的 Access 应用程序会在后台运行,Visible 和 UserControl 属性的默认值均为 False。
如果目的是让用户能够看到 Base1.accdb 的 Access 窗口并进行手动操作,可以显式设置以下属性:
• appAccess.Visible = True 用于显示 Access 窗口
• appAccess.UserControl = True 允许用户手动操作该 Access 实例
此外,建议添加适当的错误处理(Error Handling),以确保在代码执行过程中即使发生错误,也能够正确关闭 Access 实例并释放相关资源。
例如:
Private Sub Sub1()
Dim appAccess As Access.Application
On Error GoTo ErrorHandler
Set appAccess = CreateObject("Access.Application")
appAccess.Visible = True ' Make the new Access window visible
appAccess.UserControl = True ' Allow user interaction with the new instance
appAccess.OpenCurrentDatabase "D:\Access_Design\Base1.accdb"
' (Optional: Automate tasks here, e.g., appAccess.DoCmd.OpenForm "SomeForm")
' Note: Do NOT close/quit here if you want the user to interact with it.
' The user can close it manually, or add a button in Base1.accdb to quit.
ExitSub:
Set appAccess = Nothing ' Release reference, but instance remains open if UserControl=True
Exit Sub
ErrorHandler:
MsgBox "Error: " & Err.Description
If Not appAccess Is Nothing Then
appAccess.CloseCurrentDatabase
appAccess.Quit acQuitSaveNone
Set appAccess = Nothing
End If
Resume ExitSub
End Sub
希望以上信息对您有帮助。请随时向我更新情况,我很乐意提供进一步的帮助。
如果答案有帮助,请点击“接受答案”并点赞。如果您对此回答有更多疑问,请点击“评论”。
注意:如果您希望收到本帖相关的邮件通知,请按照我们文档中的步骤启用电子邮件通知。