Skip to content

Instantly share code, notes, and snippets.

@stevesohcot
Created May 17, 2016 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevesohcot/47d73642ff0c9475d99e89d0a2d141d1 to your computer and use it in GitHub Desktop.
Save stevesohcot/47d73642ff0c9475d99e89d0a2d141d1 to your computer and use it in GitHub Desktop.
Import data from SQL Server into Excel
// http://stevesohcot.com/tech-lessons-learned/2016/05/17/get-data-from-sql-server-in-excel
Public Sub GetData()
Dim strSQL As String
Dim strCnn As String
Dim cnn As Object
Dim rst As Object
strCnn = "Driver={SQL Server};" & _
"Server=SERVER_NAME_HERE;" & _
"Database=DATABASE_NAME_HERE;" & _
"Uid=USER_NAME_HERE;" & _
"Pwd=PASSWORD_HERE"
Set cnn = CreateObject("adodb.connection")
cnn.Open strCnn
Set rst = CreateObject("ADODB.Recordset")
'SQL Server: Change dbo_ to dbo.
strSQL = "SELECT * FROM ... "
rst.Open strSQL, cnn, 3, 1 '3 = Keyset, 1 = Pessemistic
If rst.RecordCount > 0 Then
rst.MoveLast
rst.MoveFirst
Do Until rst.EOF
Range("B1").FormulaR1C1 = rst.Fields("FIELD_NAME_HERE")
rst.MoveNext
Loop
rst.Close
Else
MsgBox "No data"
End If
Set rst = Nothing
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment