使用ADO将VBA连接到SQL Server - 对象已关闭

时间:2012-11-05 09:13:05

标签: sql-server-2008 excel-vba vba excel

我创建了这个对象,我可以告诉我刚刚对它进行了查询,有人能告诉我我的错误在哪里吗?

错误陈述是

“Run time error ‘3704’ operation is not allowed when the object is closed” 

它出现在这一行

ActiveWorkbook.Worksheets("SQL").Range("A1").CopyFromRecordset rspubs

我的代码是

Sub sqlTest()

Dim Sqlquery As String
Dim cnpubs As ADODB.Connection
Dim rspubs As ADODB.Recordset

' Create a connection object.
Set cnpubs = New ADODB.Connection
' Create a recordset object.
Set rspubs = New ADODB.Recordset
' Provide the connection string.
Dim strConn As String


'Construct query
Sqlquery = " sql query;”

'Use the SQL Server OLE DB Provider.

strConn = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=XXXX;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=XXXX;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=Prospects" 

'Now open the connection.
cnpubs.Open strConn

With rspubs
' Assign the Connection object.
.ActiveConnection = cnpubs
' Extract the required records.
'.Source = Sqlquery
.Open Sqlquery
' Copy the records into cell A1 on Required Sheet
ActiveWorkbook.Worksheets("SQL").Range("A1").CopyFromRecordset rspubs
End With

' Tidy Up
cnpubs.Close
rspubs.Close

Set cnpubs = Nothing

Set rspubs = Nothing


End Sub

1 个答案:

答案 0 :(得分:0)

您需要指定要运行的查询。您对Sqlquery的所有功能都是“sql query;”,它不会返回记录集。请尝试将字符串更改为Select 1 as testvalue以测试某些内容。