MS Access数据库的连接字符串不正确

时间:2016-10-12 12:29:55

标签: vba connection ms-access-2010

我正在尝试从MS Access 2007/2010数据库中推断数据。

我在VBA中有以下代码,但连接字符串不正确。我添加了相关的REFERENCES库

 Private Sub btnGetMsAccessData_Click()

Dim sConn As String
Dim oConn As ADODB.Connection
Dim oRs As ADODB.Recordset
Dim sSQL As String

sConn = "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=\\MyNetworkPath\BP-MasterDashboard Source\BP_Planning_by_PT_dept_be.accdb;Mode=Read"

Set oConn = New ADODB.Connection        ' Open a connection.
oConn.Open


sSQL = "SELECT * FROM Tbl_Start_Leaver"        ' Make a query over the connection.
Set oRs = New ADODB.Recordset
oRs.Open sSQL, , adOpenStatic, adLockBatchOptimistic, adCmdText

MsgBox oRs.RecordCount

oConn.Close ' Close the connection.
Set oConn = Nothing

End Sub

它无法在oConn.Open行上显示Unknown Application错误。

我尝试将工作簿链接到其中一个表,这样可以正常工作。 然后我看了"连接"并将其复制到我的代码中但仍然没有快乐。

继续说: 自动化错误 意外错误

任何想法都将不胜感激。

提前致谢。

1 个答案:

答案 0 :(得分:2)

虽然连接字符串不正确,但也有其他问题。例如,不将连接String分配给ADODB Connection对象以及其他对象。这是我希望可以帮助您操作的更新代码

Private Sub btnGetMsAccessData_Click()
    'Ensure you add a reference to Microsoft ADO Objects
    Dim oConn As New ADODB.Connection
    Dim oRs   As New ADODB.Recordset
    Dim sSQL  As String: sSQL = "SELECT * FROM Tbl_Start_Leaver"
    'Corrected Connection String from Thomas Inzina
    Dim sConn As String: sConn = "Provider=Microsoft.ACE.OLEDB.12.0;UID=Admin;Data Source=" & _
                                 "\\MyNetworkPath\BP-MasterDashboard Source\BP_Planning_by_PT_dept_be.accdb;Mode=Read"

    With oConn
        .ConnectionString = sConn ' You need to assign the connection string to the ADODB.Connection Object
        .Open
    End With

    'Make sure the connection isn't open before opening the recordset
    'You also need to specify which connection you want to use as the second parameter (this was missed)
    If oRs.State <> adStateOpen Then oRs.Open sSQL, oConn, adOpenStatic, adLockBatchOptimistic, adCmdText

    'Close Connection and RS
    If oConn.State = adStateOpen Then oConn.Close
    If oRs.State = adStateOpen Then oRs.Close

    'Clean Up
    Set oRs = Nothing
    Set oConn = Nothing
End Sub
相关问题