3

我已经创建了对象,我可以从中得知我刚刚对它进行了查询,谁能告诉我我的错误在哪里?

错误声明是

“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
4

1 回答 1

0

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

于 2012-11-05T16:45:33.220 回答