Excel VBA – SQL查询错误:当对象closures时不允许操作

我有一个VBA脚本,用于调用SSMS来运行查询并将结果粘贴到Excel中。 我有这个相同的代码用于其他2个查询之前,这两个都工作,但这个由于某种原因给出错误。

我原本以为这是由于临时表,所以我添加了“设置nocount在”开始,但它没有帮助。 任何提示或build议表示赞赏!

错误信息:

运行时错误“3704”:

对象closures时不允许操作。

Sub Test() 'Setup variables Dim cnn As New ADODB.Connection Dim rst As New ADODB.Recordset Dim ConnectionString As String Dim StrQuery As String Dim SOURCE As String Dim DATABASE As String Dim QUERY As String Dim intColIndex As Integer 'Assign variables SOURCE = [Data Source] DATABASE = [Database] QUERY = "set nocount on" QUERY = QUERY + " declare @Variable1 int" QUERY = QUERY + " declare @Variable2 int" QUERY = QUERY + " declare @Variable3 datetime" QUERY = QUERY + " declare @Variable4 datetime" QUERY = QUERY + " select @Variable1 = [xxxx]" QUERY = QUERY + " select @Variable2=(select Field1 from Table1 where Field2 = @Variable1)" QUERY = QUERY + " select @Variable3=min(Variable3) from Table2 where Field3=@Variable2" QUERY = QUERY + " select @Variable4=max(Field4) from Table2 where Field3=@Variable2" QUERY = QUERY + " select distinct b.Field5, b.Field10 into #Temp1" QUERY = QUERY + " from Table3 p(nolock)" QUERY = QUERY + " inner join Table4 b(nolock) on b.Field5 = p.fkField5" QUERY = QUERY + " inner join Table5 cp (nolock) on cp.Field6 = p.Field11" QUERY = QUERY + " where Field3=@Variable2 " QUERY = QUERY + " select Field3,Field9,Variable3,Field4 into #Temp2 from Table2 cf (nolock)" QUERY = QUERY + " inner join Table6 ac (nolock) on ac.Field7=cf.Field3" QUERY = QUERY + " where Variable3 >= @Variable3 - 365 and Field4 < @Variable4 + 1" QUERY = QUERY + " and ac.Field8 <>4" QUERY = QUERY + " select distinct cp.Field3,Field9,convert(varchar(10),Variable3,101) Variable3,convert(varchar(10),Field4,101) Field4" QUERY = QUERY + " from Table5 cp (nolock)" QUERY = QUERY + " inner join Table3 p (nolock) on p.Field11=cp.Field6" QUERY = QUERY + " inner join Table4 b (nolock) on b.Field5 = p.fkField5" QUERY = QUERY + " inner join #Temp1 bb on bb.Field5=b.Field5" QUERY = QUERY + " inner join #Temp2 oth on oth.Field3=cp.Field3" QUERY = QUERY + " drop table #Temp1" QUERY = QUERY + " drop table #Temp2" 'Run the query and paste results into Cell X11 on the first tab of the workbook ConnectionString = "Provider=SQLOLEDB;Data Source=" & SOURCE & "; Initial Catalog=" & DATABASE & "; Integrated Security=SSPI;" cnn.Open ConnectionString cnn.CommandTimeout = 900 StrQuery = QUERY rst.Open StrQuery, cnn Sheets(1).Range("X11").CopyFromRecordset rst 'Add the column headers For intColIndex = 0 To rst.Fields.Count - 1 Range("X10").Offset(0, intColIndex).Value = rst.Fields(intColIndex).Name Next End Sub