尝试将记录集转储到Excel 2010工作簿的选项卡时,我收到运行时错误“3704”。记录集应包含来自我使用SQL Server 2008 R2编写的存储过程的几百条记录。我知道在SQL Server Management Studio中运行时执行完全相同的语句,并且我过去使用过相同的连接字符串,因此我非常确定我的代码中的这些部分是否正常工作。
我已经研究了错误,我看到的唯一解决方案与连接超时有关。你会看到我设置了CommandTimeout = 30(我假设是以秒为单位)。我在几秒钟的时间内得到错误,所以我确信这不是我的连接超时的问题。
我的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
这是我收到的错误消息:
运行时错误'3704':
关闭对象时不允许操作。
答案 0 :(得分:1)
将SET NOCOUNT ON添加到存储过程的开头。
您可以在SQLS MS的“消息”选项卡中查看proc是否返回任何文本。诸如“受影响的100行”之类的消息将导致VBA立即关闭记录集。