Excel

Querying workbook with SQL

Ease of Use

Intermediate

Version tested with

2000, 2002 

Submitted by:

tommy bak

Description:

This code provides the capability to enter SQL-statements in a cell and run the query against other sheets in the same workbook. 

Discussion:

Using SQL directly in a worksheet as a powerful alternative to advanced filter, including the ability to join tables on two or more worksheets. The code lets you write a a complex SQL statement directly in a cell and retrive the output where you want it. This is done by referencing the ADODC.. With SQL it is also possible to query data in a closed workbook. The example file contains two examples. A query on 1 table with totals and a query that joins 2 tables. Be aware that the sample file is quite big. 

Code:

instructions for use

			

Public Sub QueryWorksheet(szSQL As String, rgStart As Range, wbWorkBook As String) Dim rsData As ADODB.Recordset Dim szConnect As String On Error GoTo ErrHandler Application.StatusBar = "Retrieving data ....." 'Set up the connection string to excel against wbWorkbook szConnect = "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & wbWorkBook & ";" & _ "Extended Properties=Excel 8.0;" Set rsData = New ADODB.Recordset 'Run the query as adCmdText rsData.Open szSQL, szConnect, adOpenForwardOnly, adLockReadOnly, adCmdText 'Check if data is returned If Not rsData.EOF Then 'if the recordset contains data put them on the worksheet rgStart.CopyFromRecordset rsData Else MsgBox "There is no records that matches the query !!", vbCritical End If 'Close connection rsData.Close 'Clean up and get out Set rsData = Nothing Application.StatusBar = False Exit Sub ErrHandler: 'an error occured in the SQL-statement MsgBox "Your query could not be executed, the SQL-statement is incorrect." Set rsData = Nothing Application.StatusBar = False End Sub Sub testsql() Dim rgPlaceOutput As Range 'first cell for the output of the query Dim stSQLstring As String 'text of the cell containing the SQL statement stSQLstring = Range("B3").Text Set rgPlaceOutput = Range("B9") 'clear the outputarea rgPlaceOutput.Resize(20000, 6).ClearContents 'Submit the querycell and the outputarea to the sub QueryWorksheet 'including the full path to the workbook. QueryWorksheet stSQLstring, rgPlaceOutput, ThisWorkbook.FullName End Sub

How to use:

  1. Copy the code into a new in the VBE.
  2. In TOOLS / References mark a reference to Microsoft ActiveX DataObject 2.X
  3. Adjust Sub testsql() to your needs (Outputcell, querycell, workbook)
  4. Save the file. The code only works on saved files.
 

Test the code:

  1. Write a SQL-statement in B3
  2. Run Sub testsql()
  3. Data will be returned starting i B9
 

Sample File:

SQL_in_Cells.zip 413.18KB 

Approved by mdmackillop


This entry has been viewed 763 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express