copyfromrecordset失败,原因是...对象已关闭

时间:2019-07-25 14:37:30

标签: sql sql-server excel vba

使用SQL Server,MS Office 365 32位,Windows 7 64位,我试图从Excel运行简单的SQL查询。它有效,但是我无法返回结果。

我试图找到解决方案并尝试了几个示例。我已经验证了我的代码可以运行,它可以在sqlserver上成功执行sql,但我无法将结果恢复为excel。失败

  

运行时错误3704。

Sub Clear_Temp_Tables()

    Dim cnn As ADODB.Connection
    Dim rst As ADODB.Recordset

    Dim ConnectionString As String
    Dim StrQuery As String

    Set cnn = New ADODB.Connection
    cnn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=xxxxxx;Data Source=xxxxxxxx\xxxxxx;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=xxxxxxx;Use Encryption for Data=False;Tag with column collation when possible=False"

    'Opens connection to the database
    cnn.Open

    cnn.CommandTimeout = 900

    StrQuery = "SELECT * FROM [blah]"

    Set rst = cnn.Execute(StrQuery)

    ' Fails HERE:
    Sheets("Data").Range("O9").CopyFromRecordset rst

    rst.Close

End Sub

0 个答案:

没有答案