Excel VBA querying from Password-Protected Access Database

后端 未结 2 1468
野性不改
野性不改 2021-01-20 19:07

I am currently trying to query one of the table from Microsoft Access Database (.mdb), however, when I try to do a SELECT * FROM myTable, it gives an \"User-def

2条回答
  •  醉梦人生
    2021-01-20 19:20

    Using ADO

    Add Reference: Microsoft ActiveX Data Objects 2.8 Library


    Sub test()
    
        Dim Conn As New ADODB.Connection
        Dim rs As New ADODB.Recordset
        Dim dbPath As String
        Dim aQuery As String
        Dim pword As String
        Dim strcon As String
    
    
        dbPath = ThisWorkbook.Path & "\Database.mdb"
        pword = "abcd"
        aQuery = "SELECT * FROM myTable"
    
        strcon = "Provider=Microsoft.Jet.OLEDB.4.0;" _
                & "Data Source=" & dbPath & ";" _
                & "Jet OLEDB:Database Password=" & pword & ";"
    
        Conn.Open strcon
        rs.Open aQuery, Conn
    
        If Not (rs.EOF And rs.BOF) Then
            MsgBox rs.Fields(0)
        End If
    
        rs.Close
        Set rs = Nothing
        Set Conn = Nothing
    
    End Sub
    

    Using DAO
    Add Reference: Microsoft DAO 3.6 Object Library

    As @Tim highlighted you have missed adding the reference to library.

    Sub test()
    
       Dim db As DAO.Database
        Dim dbPath As String
        Dim aQuery As String
        Dim pword As String
        Dim rs As DAO.Recordset
    
        dbPath = ThisWorkbook.Path & "\Database.mdb"
        pword = "abcd"
        aQuery = "SELECT * FROM myTable"
    
    
        Set db = OpenDatabase(dbPath, True, False, ";PWD=" & pword)
        Set rs = db.OpenRecordset(aQuery)
        rs.MoveFirst
        MsgBox rs.Fields(0)
    
     End Sub
    

提交回复
热议问题