Skip to content

Instantly share code, notes, and snippets.

@stevesohcot
Created August 7, 2023 14:05
Show Gist options
  • Save stevesohcot/7bf491914e147fbacb0ecdbac2827a79 to your computer and use it in GitHub Desktop.
Save stevesohcot/7bf491914e147fbacb0ecdbac2827a79 to your computer and use it in GitHub Desktop.
Import SQL Server to Excel with VBA
Public Function getDataFromRecordset()
Dim sheet As String
sheet = "Output"
Worksheets(sheet).Select
Range("A1").Select
Dim strSQL As String
strSQL = "SELECT TOP 10 * FROM table"
Dim rst As New ADODB.Recordset
rst.Open strSQL, strDbConn, adOpenKeyset, adLockOptimistic
If Not rst.EOF Then
Set rPrint = Worksheets(sheet).Range("A2")
rPrint.CopyFromRecordset rst
End If
rst.Close
Cells.Select
Selection.ColumnWidth = 50.86
Cells.EntireColumn.AutoFit
Cells.EntireRow.AutoFit
Range("A1").Select
MsgBox "Report downloaded"
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment