Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel function to make SQL-like queries on worksheet data?

I have a largish table in an Excel worksheet:

Column_1 | Column_2 | Column_3  ValueA       ValueB     ValueC .... 

What I need is a function that will take as input the range and an SQL-like query String and return a range of rows that match the query, e.g.:

=SQL_SELECT(A1:C1000, "SELECT * WHERE Column_1 = ValueH AND Column_3 = blah") 

Does something like this exist? Or what would be the best way to implement myself?

like image 428
Richard H Avatar asked Jan 06 '12 10:01

Richard H


People also ask

How do I query like SQL in Excel?

Open an SQL connection to an Excel file Before running an SQL query, you have to open a connection with the Excel file you want to access. To establish the connection, create a new variable named %Excel_File_Path% and initialize it with the Excel file path.

How do I create a SQL query in Excel?

In Excel, select Data > Queries & Connections, and then select the Queries tab. In the list of queries, locate the query, right click the query, and then select Load To. The Import Data dialog box appears. Decide how you want to import the data, and then select OK.

Is there an SQL function in Excel?

Using SQL statements in Excel enables you to connect to an external data source, parse field or table contents and import data – all without having to input the data manually. Once you import external data with SQL statements, you can then sort it, analyze it or perform any calculations that you might need.


2 Answers

You can use Get External Data (despite its name), located in the 'Data' tab of Excel 2010, to set up a connection in a workbook to query data from itself. Use From Other Sources From Microsoft Query to connect to Excel

Once set up you can use VBA to manipulate the connection to, among other thing, view and modify the SQL command that drives the query. This query does reference the in memory workbook, so doesn't require a save to refresh the latest data.

Here's a quick Sub to demonstrate accessing the connection objects

Sub DemoConnection()     Dim c As Connections     Dim wb As Workbook     Dim i As Long     Dim strSQL As String          Set wb = ActiveWorkbook     Set c = wb.Connections     For i = 1 To c.Count         ' Reresh the data         c(i).Refresh          ' view the SQL query         strSQL = c(i).ODBCConnection.CommandText         MsgBox strSQL     Next End Sub 
like image 175
chris neilsen Avatar answered Oct 02 '22 03:10

chris neilsen


If you can save the workbook then you have the option to use ADO and Jet/ACE to treat the workbook as a database, and execute SQL against the sheet.

The MSDN information on how to hit Excel using ADO can be found here.

like image 21
Jon Egerton Avatar answered Oct 02 '22 04:10

Jon Egerton