我正在尝试使用Excel 2003并将其连接到sql Server 2000以运行一些动态生成的SQL查询,这些查询最终会填充某些单元格.
我试图通过ADO通过VBA执行此操作(我已经尝试过2.8到2.0)但是在设置ADODB.Connection对象内部的ActiveConnection变量时出现错误.我需要快速解决这个问题……
Requested operation requires an OLE DB Session object,which is not supported by the current provider.
老实说,我不确定这个错误意味着什么,现在我不在乎.如何才能使此连接成功,以便我可以运行查询?
这是我的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
我想连接字符串有问题,但我尝试了十几种变体.现在我只是在黑暗中拍摄….
注意/更新:为了让事情更加混乱,如果我谷歌上面的错误报价,我得到了很多回击,但似乎没有任何相关性,或者我不确定哪些信息是相关的….
我在“Microsoft Excel Objects”下的“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