Excel VBA CodeTutorials

Export data from SQL to Excel spreadsheet using VBA

3 Mins read

In this blog, we will Import data from SQL to Excel spreadsheets using VBA. Assuming that you have a little bit of knowledge on the SQL server. Now if you are preparing reports in Excel and the data is on your SQL server then you don’t need to copy the data first from SQL server to prepare the report.
Now if your manager needs the report very frequently then you need to do the same task again and again. Frankly speaking, I faced this kind of situation in my previous company and I prepared the report using VBA and handed over the file to my manager. Now, whenever he will click the button he will get the report of the LIVE DATA from SQL to Excel.

Excel VBA Macros for Non-Coders

Do you find VBA Macros scary? Did you miss any job opportunity because of it? Get started today with our eBook guide on using – Excel VBA Macros. 140 pages of rich visuals. Download now.

Export data from SQL to Excel spreadsheet using VBA

Create-dummy-button-SQL-to-Excel

The buttons are in the above picture are basic shapes. And “HP-PC” is the system name. If you open the file in your system, it will show your system name. And the time is coming from the system’s time. After creating the above button we will create the code.

First, we are trying to focus on the Sales Report. You need to decide what will be the TSQL code for this. For Example, we need to prepare a report which will show the Name of the person and from which territory they have sold in what amount.

First of all, we need to check the TSQL code in SQL Server. I have written a simple which will pull up the records of person name and territory name and the sum of sales amount of the current year and the last year. Here is my query in the SQL server.

TSQL-code-in-SQL-server

If I ran the above query in SQL Server I am getting 17 records.

Dataset-from-SQL-query-in-Excel

Now our intention is something different. We want the same result in Excel. You can copy the result and paste it in an Excel sheet that is fine. But if you need to do the same thing every day and then you can simply copy the below code and paste it on VBA page and then connect the code with the button to get data from SQL to Excel, please follow the below steps to get the result in Excel sheet:

  • Step 1: Press Alt + F11 to go the VBA page
  • Step 2: Paste the below code
  • Step 3: Press F5 or run the code

Code

Option Explicit

'The part extracting the body is taken from here
'https://support.microsoft.com/en-us/kb/306125

Sub GetData()

Dim cnLogs As New ADODB.Connection
Dim rsHeaders As New ADODB.Recordset
Dim rsData As New ADODB.Recordset

Dim l_counter As Long: l_counter = 0
Dim strConn As String

Sheets(1).UsedRange.Clear
strConn = "PROVIDER=SQLOLEDB;"
strConn = strConn & "DATA SOURCE=(local);INITIAL CATALOG=LogData;"
strConn = strConn & " INTEGRATED SECURITY=sspi;"

cnLogs.Open strConn

With rsHeaders
.ActiveConnection = cnLogs

.Open "SELECT * FROM syscolumns WHERE id=OBJECT_ID('LogTable')"
'.Open "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'LogTable'"
'.Open "SELECT * FROM LogData.INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N'LogTable'"
'.Open "SELECT * FROM SYS.COLUMNS WHERE object_id = OBJECT_ID('dbo.LogTable')"

Do While Not rsHeaders.EOF
Cells(1, l_counter + 1) = rsHeaders(0)
l_counter = l_counter + 1
rsHeaders.MoveNext
Loop
.Close
End With

With rsData
.ActiveConnection = cnLogs
.Open "SELECT * FROM LogTable"
Sheet1.Range("A2").CopyFromRecordset rsData
.Close
End With

cnLogs.Close
Set cnLogs = Nothing
Set rsHeaders = Nothing
Set rsData = Nothing

Sheets(1).UsedRange.EntireColumn.AutoFit

End Sub

Before running the code you need to change some settings. Go to tools on the VBA page and then click on the reference and then select “Microsoft ActiveX Data Objects 2.8 Library and press OK.

VBA-page-Reference-ActiveX-Data-Objects

Now we all are good to go. Now press F5 to run the code. You will notice the same records are there in the excel sheet. Now if the data or any record is updated in the base table in SQL Server you will get the update result. Now all the time you will get the live data. That’s why it is powerful.

You can send the file to your manager or boss. He or she will get the updated report all the time. We need to assign the code to the button “Sales Report” we created earlier. Go to that button and then right-click on it and click on “Assign Macro”

Sales-Report-Assign-Macro-SQL-to-Excel-4

Then click on “New”. You will be redirected to the new VBA page. Just write “Call DataTakenFromSQLServer”. Finally, you are done. Whenever you click on the Sales Report you will get the updated result.

VBA-page-Call-DataTakenFromSQLServer-2

Now Go back to your sheet. And Click on the “Sales Report”. You will notice that the data is coming in the Excel sheet. Another one thing you will have to be careful that the SQL server service is on the form where the data is coming.

Click-Sales-Report-get-Output-SQL-to-Excel

Please download the workbook from here and check the code. Please change the SQL server name and database name to check the output of your query. You can also write your own query and check whether it is working or not. Let us know if you have any problem understanding the code. We will help you out.

Excel VBA Macros for Non-Coders

Do you find VBA Macros scary? Did you miss any job opportunity because of it? Get started today with our eBook guide on using – Excel VBA Macros. 140 pages of rich visuals. Download now.

Related posts
AlteryxTutorials

Alteryx Hotkeys - Alteryx Keyboard Shortcuts

2 Mins read
Top 50+ Alteryx Shortcuts for Windows. Alteryx is popularly known as a Self-Service Analytics tool. Business users can build their data workflows…
AlteryxTutorials

Step By Step Guide to Learn Alteryx

6 Mins read
Alteryx Learning Path: The growth in technology has resulted in growth in understanding. In today’s world, humans – fellow businessmen know the…
Excel VBA CodeTutorials

VBA Code to Clean the Date Format

1 Mins read
When it is useful? Most of the time the most annoying problem is when the data is taken from ERP or other…

6 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *