Excel VBA and Access Database

Tram Ho

Connect Excel VBA to Access Database

Using Excel Macros (VBA) you can connect to any DB such as SQL, Oracle, Access DB. So in this article we will learn how to connect to an Access DB. For Access 2007/2010 Database, Provider is: Provider = Microsoft.ACE.OLEDB.12.0 First, you must Add reference for ADO DB Connection as follows:

  1. Open VB Editor (Alt + F11).
  2. Tools -> References …
  3. Select “Microsoft ActiveX Data Objects 2.0 Library”. You can choose version 2.0 or any higher version.
  4. Click OK

Connect to Access 2007/2010 Database

USING SQL TO FILTER OR ACCESS DATA IN THE Spreadsheet

After determining how our data table, we can use SQL to access this data with the following SQL statements:

ACCESS DATA FROM EXCEL SHEETS WITH SQL

  • Accessing all data in a spreadsheet SELECT * FROM [A1:G20000] The * in this statement means we want the data of all the columns. If you use the Excel file in the video to execute these SQL statements, you need to add mi_sql to the front of the statement: mi_sql SELECT * FROM [A1: G20000]
  • Accessing data for certain columns: we write the column name after the SELECT keyword and write the columns separated by commas,

FILTER EXCEL DATA SHEET WITH SQL

  • Filter data from Excel spreadsheet with one condition: Filter data of orders from Hanoi

The above SQL statement means: from the data area A1: G20000, filter out the rows where the Region column has a value of Hanoi

  • Filter data from Excel spreadsheet with many conditions: Filter data of orders from Hanoi or Danang

In addition to using the keyword OR, we can also use the keyword IN and the SQL statement will be as follows:

  • Filter the data of sales orders with unit cost less than or equal to $ 8.99

Note: We can see in this example that the column name of this worksheet is “Unit Cost” with spaces in it. It is best to avoid error when querying data, we should not write column names with spaces or special characters (that is, do not write column names in Vietnamese with accents). {. : notice}

  • Filter the data of sales orders that have a unit cost of less than or equal to $ 8.99 sorted from the most expensive to the cheapest

In this example, we can replace [Unit Cost] in ORDER BY [Unit Cost] DESC with another column. If the data type of a column is a string, that column will be sorted from Z to A, if the data type of a column is numeric then that column will be sorted smaller.

There are many other SQL hope after this article, you can learn more.

Share the news now

Source : Viblo