I have found several use cases for my team and I to save time and utilize Excel alone for pulling data via SQL, as opposed to running queries in Access, SSRS, SSMS or Toad and then exporting that data into Excel for manipulation and analysis. There is not only the benefit of saving time by skipping the export\/import process, but also in the ability to build templates\/files and save them for quick and easy future SQL pulls. The days of needing multiple applications for your SQL pulls to import into Excel are over!<\/p>\n\n\n\n
The best use cases I’ve found that support this method are repeatable processes where the same input variables are required each time, and where the query results will not exceed the row limitations of an Excel sheet (~1M). Even in this case, you may find the first two sections of this post useful for learning about constructing and executing SQL queries<\/strong> for use outside of Excel. This alone may save you time if you are in the habit of writing long and involved queries with changing criteria.<\/p>\n\n\n\n If you are exceeding the Excel row limit but still want to work in Excel, using Power Pivot can handle this, so you may wish to utilize Power Query instead. See my post on utilizing parameters with Power Query here<\/a> for more information on how to import the data this way.<\/p>\n\n\n\n I have also found this approach to be useful when pulling data from different sources using the same criteria. It saves me lots of time.<\/p>\n\n\n\n In this example, we will construct and then run a simple SQL query using a few parameters\/variables that we enter into the spreadsheet. <\/p>\n\n\n\n Follow along so you can see how it works in practice, and then I encourage you to try it out with your own data. Once you master this method, hopefully you will find amazing ways to apply it to your own work! <\/p>\n\n\n\n A copy of the file described in this post is available for purchase – just reach out to me<\/a> for information. A more complex version that handles wildcards is also for sale.<\/p>\n\n\n\n My goal will be to run this query: Select * from Store where CreatedDate > #3\/1\/2022# and State = ‘GA’<\/strong><\/p>\n\n\n\n From here, we can either construct the SQL statement in an Excel sheet or in VBA. I have found that it is far easier to construct in an Excel sheet, especially for complex statements with many criteria. This way certainly allows for more flexibility and better troubleshooting in my opinion. Also, it’s easier to manage from a support standpoint.<\/p>\n\n\n\n Here is an overview the VBA code I wrote, that is pasted below.<\/p>\n\n\n\n I have added commentary and explanations throughout to hopefully help you to modify as needed to support your own needs.<\/p>\n\n\n\n I hope this helps you out. Below is the final look of my file for this example. I have added a button for the users to click in order to run the VBA code and execute the SQL by assigning the macro. I have formatted so the data returns in a table for easy manipulation and analysis. I have also updated the general formatting and named the sheets. <\/p>\n\n\n\n To save you time, a copy of the file is available for purchase – just reach out to me<\/a> for information.<\/p>\n\n\n\n I also have another sample template file available that allows you to put multiple criteria in a list and constructs the query accordingly, searching all items. It even allows for the use of wildcards <\/strong>by <\/strong>automatically formulating LIKE statements! <\/strong>Exciting stuff! Contact me<\/a> if interested in purchasing.<\/p>\n\n\n\n
\n\n\n\nSetting Up the Variables\/Criteria<\/strong>\/Parameters<\/strong> for Executing SQL Queries in Excel<\/strong> <\/h2>\n\n\n\n
\n
\n
Constructing the SQL Statement<\/strong><\/h2>\n\n\n\n
\n
\n
VBA Code for Executing SQL Statement and Importing the Data<\/strong><\/h2>\n\n\n\n
\n
\n
Sub SQLPull()
‘* www.bonbonsguide.com * <\/strong>
‘Importing Data into Excel using a SQL select statement in a cell <\/strong>
Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath, sconnect, sqlstring As String
Dim icols As Long
””””””””””””””””””””””””’
‘Database Name\/Path
””””””””””””””””””””””””’
DBPath = STOREDB
‘NOTE:
‘If you are querying a SQL Server or Oracle DB, use the name of the database:
‘DBPath = YourDatabaseName
‘If you are querying an Access Database, use the path to the file in quotes:
‘DBPath = “\\myfileserver\\Bonbon\\MyAccessDB.accdb” OR “F:\\Bonbon\\MyAccessDB.accdb”
””””””””””””””””””””””””’
‘Connection String
””””””””””””””””””””””””’
‘The DSN is the existing ODBC connection on your PC – this must be set up first!
‘Uncomment the applicable sconnect string for your database and modify as needed. For MS Access, no modifications should be needed.
‘SQL Server using Windows Authentication:
sconnect = “Provider=MSDASQL.1;DSN=STOREDB;DBQ=” & DBPath & “;HDR=Yes’;”
‘ORACLE Connection using an UID\/PWD:
‘sconnect = “Provider=MSDASQL.1;DSN=WAREHOUSE;uid=bonbonsguide;pwd=helpsus;DBQ=” & DBPath & “;HDR=Yes’;”
‘MS Access:
‘sconnect = “Provider = Microsoft.ACE.OLEDB.12.0; data source=” & DBPath & “;”
””””””””””””””””””””””””””””””””””””””””””””””””””””’
‘Set Timeouts (These may not be required in your environment)
””””””””””””””””””””””””””””””””””””””””””””””””””””’
Conn.ConnectionTimeout = 200
Conn.CommandTimeout = 200
””””””””””””””””””””””””’
‘Connect to datasource
””””””””””””””””””””””””’
Conn.Open sconnect
””””””””””””””””””””””””’””””””””””””””””””””””””’
‘VBA get SQL Statement from Sheet\/Named Range
””””””””””””””””””””””””’””””””””””””””””””””””””’
sqlstring = Range(“SQLstatement”)
””””””””””””””””””””””””””””””””””
‘Get the recordset – this command will execute the SQL Statement’
””””””””””””””””””””””””””””””””””
mrs.Open sqlstring, Conn
””””””””””””””””””””””””””””””””””
‘Return the Header Names
‘”””””””””””””””””””””””””””””””””’
‘If you don’t need the headers or are using your own, comment the block out
‘Where Headers will be pasted:
‘Sheet1 = Sheet identifier – use Sheets(“name of sheet”) to use sheet name instead
‘Cells (4 – indicates row 4, + 3 indicates to start in column C) \u2026 Edit this as needed
For icols = 0 To mrs.Fields.Count – 1
Sheet1.Cells(4, icols + 3).Value = mrs.Fields(icols).Name
Next
””””””””””””””””””””””””””””””””””<\/strong>
‘OPTIONAL – SPEED UP IMPORT
””””””””””””””””””””””””””””””””””<\/strong>
‘If retrieving lots of records, it may speed it up if you set calculation to manual during the import process.
‘Setting the screen updating to false may also speed up the import. Comment these out if preferred.
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
””””””””””””””””””””””””’””””””””””””””””””””””””’””””””””””””””””””””””””’
‘OPTIONAL – CLEAR DATA IN ROWS BEFORE PASTING RECORDSET OR DO OTHER PREP
””””””””””””””””””””””””’””””””””””””””””””””””””’””””””””””””””””””””””””’
‘Add your code here.
””””””””””””””””””””””””””””””””””
<\/strong>‘Paste the Rows\/Records
‘”””””””””””””””””””””””””””””””””’<\/strong>
‘Importing rows returned – the range below will be where the data starts – line this up with the headers, one row below.
Sheet1.Range(“C5”).CopyFromRecordset mrs
””””””””””””””””””””””””””””””””””<\/strong>
‘Close the Recordset
””””””””””””””””””””””””””””””””””<\/strong>
mrs.Close
””””””””””””””””””””””””””””””””””<\/strong>
‘Close Connection
””””””””””””””””””””””””””””””””””<\/strong>
Conn.Close
””””””””””””””””””””””””””””””””””<\/strong>”””””””””’
‘Turn automatic calculation and screen updating back on.
””””””””””””””””””””””””””””””””””<\/strong>”””””””””’
Application.Calculation = xlCalculationAutomatic
Application.Calculate
Application.ScreenUpdating = True
End Sub<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n
\n\n\n\nWrapping Up<\/strong><\/h2>\n\n\n\n