Created
May 17, 2016 00:33
-
-
Save stevesohcot/47d73642ff0c9475d99e89d0a2d141d1 to your computer and use it in GitHub Desktop.
Import data from SQL Server into Excel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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