如何在 Excel VBA 和 Access 中使用 DAO 停止密码提示

How to stop password prompt using DAO in Excel VBA and Access

我正在使用 DAO 在 Excel 中使用 vba 在受密码保护的 Access 数据库上 运行 查询,偶尔 运行 宁 Access 的子实例是打开时连同 window 询问数据库密码,不输入密码并按取消没有区别,查询仍然 运行s 并显示输出,有什么方法可以停止访问打开并询问密码?

Dim MyDatabase As DAO.Database
Dim MyQueryDef As DAO.QueryDef
Dim MyRecordset As DAO.Recordset
Dim DB_Name As String
Dim cond As String
Dim pWord As String

Dim wb As Workbook: Set wb = ThisWorkbook
With wb

    On Error GoTo ErrHandler:

    clearRange.Value = ""

    DB_Name = DataBname()
    pWord = pwd()

    Set MyDatabase = DBEngine.Workspaces(0).OpenDatabase(DB_Name, False, True, pWord)
    Set MyQueryDef = MyDatabase.QueryDefs(queryName) 'Query Name

    Set MyRecordset = MyQueryDef.OpenRecordset 'Open the query
    pasteRange.CopyFromRecordset MyRecordset

    failRange.Value = False

My_Exit:

    If MyRecordset Is Nothing Then
        'Do Nothing
    Else
        MyRecordset.Close
        Set MyRecordset = Nothing
    End If
    If MyDatabase Is Nothing Then
        'Do Nothing
    Else
        MyDatabase.Close
        Set MyDatabase = Nothing
    End If

End With

Exit Sub

ErrHandler:

MsgBox Err.Description
failRange.Value = True
Resume My_Exit

End Sub

Function pwd() As String

pwd = "MS Access;PWD=password"

End Function

您的代码没有任何问题。 使用 Access 2003 后端测试。 可能是如果您使用 Access 2007 及更高版本,您必须在数据库选项中设置对遗留密码的处理。

此致

要解决此问题,您必须将工作簿中的引用从 DAO.36 更改为 Microsoft Office XX.0 Access 数据库引擎对象库。

我用 Access 2010Access 2013 测试了代码,它工作正常。

此致