无法打开 MS-Access ADO 连接

unable to open MS-Access ADO connection

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

错误是"Object variable or With block variable not set"

我正在使用 excel 2010,我的数据库在 Access 2010 中,我还添加了对 "Microsoft ActiveX Data Objects 2.8 library"

的引用

任何帮助将不胜感激

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

我刚刚在连接中添加了一个 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