title: Run-time error '3704':Operation is not allowed when the object is closed
body: <p>I am trying to run code in VBA and I am getting the following error </p>
  
  <p>"Run-time error '3704':Operation is not allowed when the object is closed."</p>
  
  <p>I am running a SQL query and when running it I get this error, but if I run a much simpler SQL query it works with no issue. </p>
  
  <pre class="lang-vb prettyprint-override"><code>Sub macro()
  
  Dim entry as String, query As string , ostatni_rzad As Integer, rw_name As String Dim data_source As String
  Dim initial_catalog As String
  Dim server_for_DE As String
  Dim data_source_for_DE As String
  
  query = "Use database SET NOCOUNT ON Declare  Set @valueId = 139 set @matruirtyPeriodInt = 677 
  Set @curveIdList = char(39)+ '432' + char(39) + ',' + char(39) +  '432433424' + Char(39)Set @EffectiveDate = '01/01/2001' 
  Set @bondEquivalentEffectiveDate = '01/01/2001' Set @simulationName = 'mysimulation' Select  top 1       @simulationId = simulationId,       @batchLoadId = BatchloadId 
  From     myserver with(nolock) Where  [name] = @simulationName  And   Effectivedate = @EffectiveDate  Order by startDate desc 
  Select  top 1 @bondEquiValentsimulationId = simulationId ,  @durationEquiValentBatchLoadId = BatchloadId From   myserver with (nolock) 
  Where    [name] = @bondEquivalentSimulationName and  Effectivedate =  @bondEquivalentEffectiveDate Order by  startDate desc   Select  @linkServerName = LinkServerName ,  @databaseName = DatabaseName 
  From   myserver L with (nolock)Left    Outer Join  myserver R with (nolock) 
  On     L.DatabaseId = R.simulationStorageDatabaseId Where R.simulationId = @simulationId;  
  WITH cte AS 
  
  (SELECT    x,y,z,w,u,ROW_NUMBER() OVER (PARTITION BY x ORDER BY y) AS rn   From mybase with (nolock) Where simulationid = @bondEquiValentsimulationId , 
  
  GROUP BY x,y,z,w,u) 
  
  
  Select * FROM cte WHERE rn = 1
  "
  
  entry = "Provider=SQLOLEDB.1;Data Source=" &amp; data_source &amp; ";Initial Catalog=" &amp; initial_catalog &amp; ";Integrated Security=SSPI"
  
  Set Cn = New ADODB.Connection
      With Cn
      .CommandTimeout = kpkp 'fds
      .Open dccurnx
      End With
  
      Set rs = New ADODB.Recordset
  
      With rs
              .ActiveConnection = Cn
  
              .Open query
  End With
  
     ostatni_rzad = ThisWorkbook.Sheets(2).UsedRange.Row - 1 + ThisWorkbook.Sheets(2).UsedRange.Rows.Count
      ThisWorkbook.Sheets(2).Cells(ostatni_rzad + 1, 1).CopyFromRecordset rs
  </code></pre>
  
  <p>And in this last line is where I get the error</p>