【问题标题】:unable to open MS-Access ADO connection无法打开 MS-Access ADO 连接
【发布时间】:2016-11-28 14:11:29
【问题描述】:

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

错误是“对象变量或未设置块变量”

我使用的是 excel 2010,我的数据库在 Access 2010 中,我还添加了对“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

【问题讨论】:

  • 我认为该错误与另一段代码有关。你能把整个过程贴出来吗?
  • @Rdster : 我刚刚添加了整个代码
  • 将 sdbpath 变量放入连接字符串时会发生什么? con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sdbpath & ";Persist Security Info=False;"
  • 在我看来,您在Dim con As New ADODB.Connection 中错过了New,因此没有创建对象
  • 感谢@MartinDreher:Dim con As New ADODB.Connection 工作得很好。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 2014-10-15
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多