Created
August 7, 2023 14:05
-
-
Save stevesohcot/7bf491914e147fbacb0ecdbac2827a79 to your computer and use it in GitHub Desktop.
Import SQL Server to Excel with VBA
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
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