title: Accessing SQL Database in Excel-VBA
body: <p>I am copying an VBA code snippet from MSDN that shows me how to grab results from a SQL query into excel sheet (Excel 2007):</p>
  
  <pre><code>Sub GetDataFromADO()
  
      'Declare variables'
          Set objMyConn = New ADODB.Connection
          Set objMyCmd = New ADODB.Command
          Set objMyRecordset = New ADODB.Recordset
  
      'Open Connection'
          objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;User ID=abc;Password=abc;"
          objMyConn.Open
  
      'Set and Excecute SQL Command'
          Set objMyCmd.ActiveConnection = objMyConn
          objMyCmd.CommandText = "select * from myTable"
          objMyCmd.CommandType = adCmdText
          objMyCmd.Execute
  
      'Open Recordset'
          Set objMyRecordset.ActiveConnection = objMyConn
          objMyRecordset.Open objMyCmd
  
      'Copy Data to Excel'
          ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)
  
  End Sub
  </code></pre>
  
  <p>I have already added Microsoft ActiveX Data Objects 2.1 Library under as a reference. And this database is accessible.</p>
  
  <p>Now, when I run this subroutine, it has an error:</p>
  
  <p>Run-time error 3704: Operation is not allowed when object is closed.</p>
  
  <p>On the statement:   </p>
  
  <pre><code>ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)
  </code></pre>
  
  <p>Any idea why?</p>
  
  <p>Thanks.</p>