保护 Microsoft Access 数据库有两种方式:
- 一种是为各个 MDB 设置密码。虽然在 DAO 中您可以使用 OpenDatabase 方法在不出现密码提示的情况下打开此类数据库,但这在 Access 2002 之前的版本中是无法做到的。Access 2002 的 Application.OpenCurrentDatabase 方法包括一个可用于指定数据库密码的可选参数。
- 第二种方法是提供一系列用户名和密码来保护 Access 本身。在这种情况下,通过使用 Shell 命令和 GetObject 方法可以避免用户名和密码提示。
使用 Shell 命令打开受保护的 Access 数据库的主要问题在于,Access 只有在失去一次焦点后才会在运行对象表中注册其自身。这意味着,只有在 Access 失去焦点后,才能通过调用 GetObject 找到它并实现自动化。下面的 Visual Basic 代码将演示如何启动受保护的 Access 数据库并获取 Access 的运行实例,以便将 Access 自动化。
分步示例
- 在 Visual Basic 中打开一个新的标准 EXE 项目。默认情况下会创建 Form1。
- 从“项目”菜单中选择“引用”,选中“Microsoft Access 8.0 对象库”,然后单击“确定”。对于 Access 2000,请选中“Microsoft Access 9.0 对象库”。对于 Access 2002,请选中“Microsoft Access 10.0 对象库”。
- 向 Form1 中添加一个 CommandButton 并将以下代码添加到 Form1 的代码窗口中: Private Declare Sub Sleep Lib "Kernel32" (ByVal dwMS As Long) Private Sub Command1_Click() Dim accObj As Access.application, Msg As String Dim application As String, dbs As String, workgroup As String Dim user As String, password As String, cTries As Integer Dim x ' This is the default location of Access application = "C:\Program Files\Microsoft Office\Office\MSACCESS.EXE" ' Use the path and name of a secured MDB on your system dbs = "C:\TestDatabase.mdb" ' This is the default workgroup workgroup = "C:\Windows\System\System.mdw " user = "Admin" ' Use a valid username password = "Mypassword" ' and correct password x = Shell(application & " " & Chr(34) & dbs & Chr(34) & " /nostartup /user " & user & _ " /pwd " & password & " /wrkgrp " & Chr(34) & workgroup & Chr(34), vbMinimizedFocus) On Error GoTo WAITFORACCESS Set accObj = GetObject(, "Access.Application") ' Turn off error handling On Error GoTo 0 ' You can now use the accObj reference to automate Access Msg = "Access is now open. You can click on Microsoft Access " Msg = Msg & "in the Taskbar to see that your database is open." Msg = Msg & vbCrLf & vbCrLf & "When ready, click OK to close." MsgBox Msg, , "Success!" accObj.CloseCurrentDatabase accObj.Quit Set accObj = Nothing MsgBox "All Done!", vbMsgBoxSetForeground Exit Sub WAITFORACCESS: ' <--- This line must be left-aligned. ' Access isn't registered in the Running Object Table yet, so call ' SetFocus to take focus from Access, wait half a second, and try ' again. If you try five times and fail, then something has probably ' gone wrong, so warn the user and exit. SetFocus If cTries < 5 Then cTries = cTries + 1 Sleep 500 ' wait 1/2 seconds Resume Else MsgBox "Access is taking too long. Process ended.", _ vbMsgBoxSetForeground End If End Sub
- 运行该项目并单击“Command1”。您的受保护的 MDB 将在不出现提示的情况下打开,并会显示一个暂停该代码的消息框,以便您可以验证您的数据库是否已真的打开。然后,您可以单击“确定”退出该消息框并关闭 Access。