2016-10-12 67 views
0

我想从MS Access 2007/2010数据库中推断数据。MS Access数据库的连接字符串不正确

我在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行上的未知应用程序错误。

我试图将一个工作簿链接到其中一个表格,这工作正常。 然后我看着“连接”并将其复制到我的代码中,但仍然没有快乐。

口口声声说: 自动化错误 意外错误

任何想法,将不胜感激。

在此先感谢。

回答

2

虽然连接字符串不正确,但还有其他问题。例如,不将连接字符串分配给ADODB连接对象以及其他连接对象。这里是更新后的代码,我希望能让你运作

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 
+0

这没有奏效。我想也许它是我需要的一个lib引用。 – mond007

+0

请参阅我对代码第2行的评论。您需要对ADO的引用。特别是“Microsoft ActiveX数据对象2.X库”,或者你可能有版本6.x可用。要么应该工作。 –

+0

我有Microsoft ActiveX数据对象6.1库 - 所以它似乎这不是问题。 – mond007

相关问题