3
我已經創建了該對象,並且從中我可以告訴我只對它執行了一個查詢,任何人都可以告訴我我的錯誤在哪裏?使用ADO將VBA連接到SQL服務器 - 對象關閉
的錯誤說法是
「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
我假設文本只是爲了在線發佈而添加的,並且它們實際上具有但是這個想法仍然有效,你的查詢實際上是否有效? – Brad
@Brad Good Point!對於OP,您可能需要在查詢頂部添加'SET NOCOUNT ON'。從SQL Server中抑制表示(x行受影響)的消息。 – deusxmach1na