请求的操作需要OLE DB会话对象… – 通过ADO将Excel连接到SQL服务器

我试图把Excel 2003连接到SQL Server 2000来运行一些dynamic生成的SQL查询,最终填充某些单元格。

我试图通过VBA通过ADO(我试过2.8到2.0),但我在设置ADODB.Connection对象内的ActiveConnectionvariables时出现错误。 我需要解决这个很快…

请求的操作需要一个OLE DB会话对象,目前的提供者不支持。

我真的不知道这个错误意味着什么,现在我不在乎。 如何才能使这个连接成功,以便我可以运行我的查询?

这是我的VB代码:

 Dim SQL As String, RetValue As String SQL = " select top 1 DateTimeValue from SrcTable where x='value' " 'Not the real SQL RetValue = "" Dim RS As ADODB.Recordset Dim Con As New ADODB.Connection Dim Cmd As New ADODB.Command Con.ConnectionString = "Provider=sqloledb;DRIVER=SQL Server;Data Source=Server\Instance;Initial Catalog=MyDB_DC;User Id=<UserName>;Password=<Password>;" Con.CommandTimeout = (60 * 30) Set Cmd.ActiveConnection = Con ''Error occurs here. ' I'm not sure if the rest is right. I've just coded it. Can't get past the line above. Cmd.CommandText = SQL Cmd.CommandType = adCmdText Con.Open Set RS = Cmd.Execute() If Not RS.EOF Then RetValue = RS(0).Value Debug.Print "RetValue is: " & RetValue End If Con.Close 

我想象连接string有问题,但我已经尝试了十几个变种。 现在我只是在黑暗中拍摄….

注意/更新 :为了使事情更混乱,如果我上面的错误报价谷歌,我得到了很多点击回来,但没有什么似乎相关,或者我不知道什么信息是相关的….

我在“Microsoft Excel对象”下的“Sheet1”中获得了VBA代码。 我以前做过,但通常把东西放在一个模块中。 这可能会有所作为吗?

你还没有打开你的连接。 我认为在将其分配给Command对象之前,您需要一个Con.Open

 Con.ConnectionString = "Provider=sqloledb;DRIVER=SQL Server;Data Source=Server\Instance;Initial Catalog=MyDB_DC;User Id=<UserName>;Password=<Password>;" Con.CommandTimeout = (60 * 30) Con.Open Set Cmd.ActiveConnection = Con 'Error occurs here. Cmd.CommandText = SQL Cmd.CommandType = adCmdText