title: Using Excel VBA to run SQL query
body: <p>I am fairly new to SQL and VBA. I have written a SQL query that I would like to be able to call and run from a VBA sub in an excel workbook and then bring the query results into the workbook. I have found some subs online (stackoverflow and other places) that claim to do this but I am having trouble understanding them as they contain no explanation. For example, here is a sub that I found online:</p>
  
  <pre class="lang-vb prettyprint-override"><code>Sub ConnectSqlServer()
  
      Dim conn As ADODB.Connection
      Dim rs As ADODB.Recordset
      Dim sConnString As String
  
      ' Create the connection string.
      sConnString = "Provider=SQLOLEDB;Data Source=INSTANCE\SQLEXPRESS;" &amp; _
                    "Initial Catalog=MyDatabaseName;" &amp; _
                    "Integrated Security=SSPI;"
  
      ' Create the Connection and Recordset objects.
      Set conn = New ADODB.Connection
      Set rs = New ADODB.Recordset
  
      ' Open the connection and execute.
      conn.Open sConnString
      Set rs = conn.Execute("SELECT * FROM Table1;")
  
      ' Check we have data.
      If Not rs.EOF Then
          ' Transfer result.
          Sheets(1).Range("A1").CopyFromRecordset rs
      ' Close the recordset
          rs.Close
      Else
          MsgBox "Error: No records returned.", vbCritical
      End If
  
      ' Clean up
      If CBool(conn.State And adStateOpen) Then conn.Close
      Set conn = Nothing
      Set rs = Nothing
  
  End Sub
  </code></pre>
  
  <p>First of all, would this work? Second, what do I need to replace in the sub (it looks like provider, data source, initial catalog, etc) and where do I find the info to replace them with?</p>
  
  <p>I hope this question is not too confusing and I appreciate your help!</p>