2016-10-12 99 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

相關問題