无法打开MS-Access ADO连接

时间:2016-11-28 14:11:29

标签: excel vba ms-access access-vba ms-access-2010

我正在尝试通过excel VBA使用ADODB.Connection对象打开Access数据库连接,但是在打开连接时收到错误。

错误是"对象变量或没有设置块变量"

我正在使用excel 2010,我的数据库在Access 2010中,我还添加了对#34; Microsoft ActiveX Data Objects 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

1 个答案:

答案 0 :(得分: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