Skip to main content

Use SQL Query in Excel VBA


If you are an SQL junkie then using SQL in Excel VBA would be a good choice.

If just starting to embark on the SQL world, then it would be a fun also to use SQL statement in Excel VBA.

To start SQL queries in Excel VBA, it will need to reference to "Microsoft Activex Data Object 6.1 Library".

If Microsoft Activex Data Object 6.1 Library, is not found on the system.

Please refer to this Microsoft link:
https://support2.microsoft.com/kb/2640696?wa=wsignin1.0

To add reference using Excel VBA, press "Alt + F11" to open Excel VBA Project Window.

Click on "Tools" and click "References", then browse for Microsoft Activex Data Object 6.1 Library and click ok.

Or check out link below for the screen shot on how to add References in Excel VBA.

This link has screen shots on how to add references.
http://quickbytesstuff.blogspot.sg/2014/09/excel-vba-speak-method.html

Once the Activex Library is added, then it's time to code and have some fun.

There are two VBA code snippet below:

1. First VBA code, will search for the instances of string occurences and display the value on the next column.
   This first code, got a simple and basic SQL query to search for a string.

2. Second VBA code, will search for a particular string occurrence, plus another string value.
   And if the two value matches, it will be displayed on next columns.

First SQL statement is just like this:
SELECT * FROM [Sheet1$] WHERE [Colors of the Night] = 'Yellow'

It will find for "Yellow"  on the column labeled as "Colors of the Night".

The dollar sign at the end of Sheet1 is needed, or else VBA will throw an error.


Worksheet looks like this image below:
"Colors of the Night" is on A1 cell as reference, to the SQL Statement.



If the Excel VBA is not able to find the value specified on the SQL query.

Like, if "Colors of the Night" is not found on Sheet1.

VBA will show 'Run-time error' No value given for one or more required parameters.

The image shown  above is the data used for testing on this VBA code.

Its for illustration and sample purposes only. But the concept should be the same on any actual data.


Here's the VBA code for example number 1:

Sub SQL_VBA_1()

    Dim connect_Str As String

    Dim query As String

    Dim rstRecordset As ADODB.Recordset
    
    Dim fileName As String
    
    Range("B:B").Clear
    fileName = "D:\book1sql.xlsm"

    connect_Str = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
               "Data Source=" & fileName & ";" & _
               "Extended Properties=Excel 12.0"

    
    query = "SELECT * FROM [Sheet1$] WHERE [Colors of the Night] = 'Yellow'"

  Set rstRecordset = New ADODB.Recordset
  rstRecordset.Open _
  Source:=query, _
  ActiveConnection:=connect_Str, _
  CursorType:=adOpenUnspecified, _
  LockType:=adLockReadOnly, _
  Options:=adCmdText

     rstRecordset.Fields.Refresh
    
        Range("B2").CopyFromRecordset rstRecordset
        'MsgBox rstRecordset.Fields.Count

    Dim cell As Range, i As Long
    With Range("A1").CurrentRegion
        For i = 0 To rstRecordset.Fields.Count - 1
            .Cells(1, i + 1).Value = rstRecordset.Fields(i).Name
        Next i
        .EntireColumn.AutoFit
        
    End With

rstRecordset.Close
Set rstRecordset = Nothing

End Sub


If everything goes fine, worksheet output will look like this:




Second SQL statement is this:
SELECT * FROM [Sheet1$] WHERE [Colors of the Night] = 'Yellow' And [Day] = 'Saturday'

This SQL statement has two "WHERE" clauses if neither one does not satisfy the value, then result will be empty.

Sample excel worksheet data looks like this image below:


Here's the VBA code for example number 2:

Sub SQL_VBA_2()

Dim connect_Str As String

    Dim query As String

    Dim rstRecordset As ADODB.Recordset
    
    Dim fileName As String
    fileName = "D:\book1sql.xlsm"

    connect_Str = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
               "Data Source=" & fileName & ";" & _
               "Extended Properties=Excel 12.0"  
    
    
    query = "select * from [Sheet1$] where [Colors of the Night] = 'Yellow' and [Day] = 'Saturday'"


  Set rstRecordset = New ADODB.Recordset
  rstRecordset.Open _
  Source:=query, _
  ActiveConnection:=connect_Str, _
  CursorType:=adOpenUnspecified, _
  LockType:=adLockReadOnly, _
  Options:=adCmdText

     rstRecordset.Fields.Refresh
    
        Range("D2").CopyFromRecordset rstRecordset
        'MsgBox rstRecordset.Fields.Count

    Dim cell As Range, i As Long
    With Range("A1").CurrentRegion
        For i = 0 To rstRecordset.Fields.Count - 1
            .Cells(1, i + 1).Value = rstRecordset.Fields(i).Name
        Next i
        .EntireColumn.AutoFit
        
    End With

rstRecordset.Close
Set rstRecordset = Nothing

End Sub


If the query is successful, result will be like this, two yellow Saturday nights:



There are of course instances, where just a pure VBA code will do the job. Need to weigh down what would be the best choice to use.

Mileage will always vary, if you find SQL query statements easy to use then it will be not be hard to use it on Excel VBA.

Hope it helps to get started on how to use SQL queries in VBA.


Enjoy VBA coding..and have fun!!!

see labels below, for more VBA...

Comments

Popular posts from this blog

Notepad++ convert multiple lines to a single line and vice versa

Notepad++ is an awesome text editing tool, it can accept regex to process the text data. If the data is in a “.csv” format or comma separated values which is basically just a text file that can either be opened using a text editor, excel or even word. Notepad++ can process the contents of the file using regex. Example if the data has multiple rows or lines, and what is needed is to convert the whole lines of data into a single line. Notepad++ can easily do it using regex. However, if the data is on a single line and it needs to be converted into multiple lines or rows then regex can also be used for this case. Here’s an example on how to convert multiple rows or lines into a single line. Example data: Multiple rows, just a sample data. Press Ctrl+H, and  on "Find what" type: [\r\n]+ and on "Replace with" type with: , (white space) --white space is needed if need to have a space in between the data. See image below, "Regular Expression" must be se

WMIC get computer name

WMIC get computer model, manufacturer, computer name and  username. WMIC is a command-line tool and that can generate information about computer model, its manufacturer, its username and other informations depending on the parameters provided. Why would you need a command line tool if there’s a GUI to check? If you have 20 or 100 computers, or even more. It’s quite a big task just checking the GUI to check the computer model and username. If you have remote computers, you need to delegate someone in the remote office or location to check. Or you can just write a batch file or script to automate the task. Here’s the code below on how get computer model, manufacturer and the username. Open an elevated command prompt and type:     wmic computersystem get "Model","Manufacturer", "Name", "UserName" Just copy and paste the code above, the word “computersystem” does not need to be change to a computer name. A

How to check office version from command line

The are quite a few ways to check office version it can be done via registry, PowerShell or VBScript and of course, good old command line can also do it. Checking Windows office version whether it is Office 2010, Office, 2013, Office 2016 or other version is quite important to check compatibility of documents; or just a part of software inventory. For PowerShell this simple snippet can check the office version: $ol = New-Object -ComObject Excel.Application $ol . Version The command line option will tell you where’s the path located; the result will also tell whether office is 32-bit, 64-bit and of course the version of the office as well. Here’s the command that will check the office version and which program directory the file is located which will tell whether it’s 32-bit or 64-bit. Command to search for Excel.exe: DIR C:\ /s excel.exe | find   /i "Directory of"  Above command assumes that program files is on  C: drive. Sample Outpu