2016-11-28 162 views
0

我想通過excel VBA使用ADODB.Connection對象打開Access數據庫連接,但打開連接時出現錯誤。無法打開MS-Access ADO連接

的錯誤是「對象變量或帶塊變量未設置」

我使用2010的Excel,我的數據庫是Access 2010,我還增加了對「Microsoft ActiveX數據對象2.8庫」

任何幫助將高度讚賞

Dim con As ADODB.Connection 

con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\vk10084\Desktop\Jobs\PnL\MyDatabaseFiles\Database1.accdb;Persist Security Info=False;" 

編輯:

以下是整個代碼

Dim con As ADODB.Connection 
Dim rs As ADODB.Recordset 
Dim sconString As String 
Dim sdbpath As String 
Dim sCommand As String 

sdbpath = ThisWorkbook.Path & "\Database1.accdb" 
sCommand = "INSERT INTO Employees VALUES('Vikas Kumar', '263763')" 

Dim cmd As New ADODB.Command 

con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\vk10084\Desktop\Jobs\PnL\POC on Access\Database1.accdb;Persist Security Info=False;" 


cmd.ActiveConnection = con 

cmd.CommandText = sCommand 
cmd.Execute 

con.Close 
+0

我會認爲這個錯誤與另一段代碼有關。你可以發佈整個程序嗎? – Rdster

+0

@Rdster:我剛剛添加了整個代碼 – braceyourself

+0

將sdbpath變量放入連接字符串時會發生什麼? 'con.Open「Provider = Microsoft.ACE.OLEDB.12.0; Data Source =」&sdbpath & "; Persist Security Info = False;「' – Rdster

回答

2

我只是增加了一個New到連接和輕微重新排序的代碼,使其更具可讀性。這是否工作?

Dim Con As New ADODB.Connection 
With Con   
    .ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\vk10084\Desktop\Jobs\PnL\POC on Access\Database1.accdb;Persist Security Info=False;" 
    .Open 
End With 

Dim Cmd As New ADODB.Command 
With Cmd 
    .ActiveConnection = Con 
    .CommandType = adCmdText 
    .CommandText = sCommand 
    .Execute 
End With 
+0

感謝Martin,它的工作原理 – braceyourself

+0

太棒了!答案 –