简体   繁体   English

Excel VBA运行时错误'3704'

[英]Excel VBA Run-time Error '3704'

I am getting run-time error '3704' when trying to dump a recordset into the tab of an Excel 2010 workbook. 尝试将记录集转储到Excel 2010工作簿的选项卡时遇到运行时错误“ 3704”。 The recordset should contain a couple of hundred records that come from a stored procedure I wrote using SQL Server 2008 R2. 记录集应包含数百条记录,这些记录来自我使用SQL Server 2008 R2编写的存储过程。 I know the exact same statement executes when ran in SQL Server Management Studio and I have used the same connection string in the past so I am pretty sure those parts of my code are working correctly. 我知道在SQL Server Management Studio中运行时会执行完全相同的语句,并且过去使用过相同的连接字符串,因此,我很确定代码的那些部分可以正常工作。

I have researched the error and the only solutions I have seen have to do with the connection timing out. 我已经研究了错误,并且看到的唯一解决方案与连接超时有关。 You will see that I have set CommandTimeout = 30 (I assume that is in seconds). 您将看到我已将CommandTimeout设置为30(我假设以秒为单位)。 I get the error in just a few seconds of clock time so I am sure that this is not a problem with my connection timing out. 我在短短的几秒钟内就收到了错误消息,因此我确信这不是我的连接超时问题。

My VBA code: 我的VBA代码:

Sub Add_Results_Of_ADO_Recordset()

    Dim cnt As ADODB.Connection
    Dim rst As ADODB.Recordset
    Dim stSQL As String
    Dim wbBook As Workbook
    Dim wsSheet As Worksheet
    Dim rnStart As Range


    Const stADO As String = "Provider=SQLOLEDB.1;User ID =xxxxx;Password=xxxxx;" & _
    "Persist Security Info=False;" & _
    "Initial Catalog=MyDatabase;" & _
    "Data Source=xxxxxxxxxxxx"

    Set wbBook = ActiveWorkbook
    Set wsSheet = wbBook.Worksheets(1)

    With wsSheet
        Set rnStart = .Range("TopLeft").Offset(1, 0)
    End With

    Set cnt = New ADODB.Connection

    With cnt
        .CursorLocation = adUseClient
        .Open stADO
        .CommandTimeout = 30
    End With

    stSQL = "EXEC MyDatabase.dbo.PolicyList '2/1/2014','2/1/2014','BOOK'"


    With cnt
     Set rst = .Execute(stSQL)
    End With

    'Dump recordset into my WorkBook
    rnStart.CopyFromRecordset rst    'This is where the error occurs!!!


     'Cleaning up.
    rst.Close
    cnt.Close
    Set rst = Nothing
    Set cnt = Nothing

End Sub

This is the error message I get: 这是我收到的错误消息:

Run-time error '3704': 运行时错误“ 3704”:

Operation is not allowed when object is closed. 关闭对象时,不允许进行操作。

Add SET NOCOUNT ON to the head of your stored proc. 将SET NOCOUNT ON添加到存储过程的开头。

You can see if the proc is returning any text in the Messages tab in SQLS MS. 您可以在SQLS MS的“消息”选项卡中查看proc是否返回任何文本。 Messages like '100 rows affected' will cause VBA to close the recordset immediately. 诸如“受影响的100行”之类的消息将导致VBA立即关闭记录集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM