Skip to Content
Course content

4.2. Writing SQL Queries in VBA

In Microsoft Access, SQL (Structured Query Language) is used to interact with databases. Writing SQL queries in VBA (Visual Basic for Applications) allows you to automate database operations such as retrieving, updating, inserting, or deleting data through Access forms, reports, and macros. VBA provides a powerful way to interact with the underlying database and execute SQL queries dynamically.

This section will explain how to write and execute SQL queries in VBA, covering the following topics:

  1. Executing SQL Queries in VBA
  2. Using SQL to Retrieve Data
  3. Using SQL for Data Modification
  4. Dynamic SQL Queries in VBA
  5. Handling SQL Errors

1. Executing SQL Queries in VBA

To execute SQL queries in VBA, Access provides the DoCmd object and DAO or ADO libraries.

  • DoCmd Object: You can use the DoCmd.RunSQL method to execute action queries (such as INSERT, UPDATE, or DELETE) directly in VBA.
  • DAO or ADO: For more complex queries that return data (like SELECT queries), you can use DAO Recordsets or ADO Recordsets.

Example 1: Using DoCmd.RunSQL for Action Queries

DoCmd.RunSQL "UPDATE Employees SET Salary = 50000 WHERE EmployeeID = 1"

This will update the salary of the employee with EmployeeID = 1 to 50,000.

Example 2: Using DAO for Select Queries

Dim db As Database
Dim rs As Recordset

Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM Employees WHERE Department = 'Sales'")

' Loop through the records
Do While Not rs.EOF
    Debug.Print rs!EmployeeName & " - " & rs!Salary
    rs.MoveNext
Loop

rs.Close
Set rs = Nothing
Set db = Nothing

This will open a recordset of employees in the "Sales" department and print their names and salaries.

2. Using SQL to Retrieve Data

SQL SELECT queries are used to retrieve data from one or more tables. You can execute SELECT queries using VBA to populate forms, reports, or manipulate data in Access.

Example 1: Simple Select Query

Dim db As Database
Dim rs As Recordset

Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT EmployeeName, Salary FROM Employees WHERE Department = 'Marketing'")

' Loop through the recordset and display employee names and salaries
Do While Not rs.EOF
    Debug.Print rs!EmployeeName & " - " & rs!Salary
    rs.MoveNext
Loop

rs.Close
Set rs = Nothing
Set db = Nothing

In this example, the SELECT query retrieves employees' names and salaries from the "Marketing" department.

Example 2: Using SQL with Criteria

You can also use criteria (conditions) in a SELECT query to filter results.

Dim db As Database
Dim rs As Recordset

Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM Employees WHERE Salary > 60000")

' Loop through the recordset and display employee details
Do While Not rs.EOF
    Debug.Print rs!EmployeeName & " - " & rs!Salary
    rs.MoveNext
Loop

rs.Close
Set rs = Nothing
Set db = Nothing

This query filters employees with a salary greater than 60,000.

3. Using SQL for Data Modification

SQL is often used for modifying data in the database. This includes INSERT, UPDATE, and DELETE operations. These are known as action queries.

Example 1: Inserting Data into a Table

You can use an INSERT INTO query to add records to a table.

DoCmd.RunSQL "INSERT INTO Employees (EmployeeName, Department, Salary) VALUES ('John Doe', 'Sales', 55000)"

This will insert a new employee record into the "Employees" table.

Example 2: Updating Data in a Table

You can use an UPDATE query to modify existing records in a table.

DoCmd.RunSQL "UPDATE Employees SET Salary = 60000 WHERE EmployeeID = 1"

This updates the salary of the employee with EmployeeID = 1 to 60,000.

Example 3: Deleting Data from a Table

You can use a DELETE query to remove records from a table.

DoCmd.RunSQL "DELETE FROM Employees WHERE EmployeeID = 2"

This deletes the employee with EmployeeID = 2 from the table.

4. Dynamic SQL Queries in VBA

Dynamic SQL queries allow you to build SQL statements based on user input or other variables within your VBA code. This is useful when you need to execute SQL queries based on changing conditions, such as filtering data by different criteria.

Example: Dynamic WHERE Clause Based on User Input

Dim department As String
department = InputBox("Enter the department name:")

Dim db As Database
Dim rs As Recordset
Dim sql As String

sql = "SELECT EmployeeName, Salary FROM Employees WHERE Department = '" & department & "'"
Set db = CurrentDb
Set rs = db.OpenRecordset(sql)

' Loop through the records
Do While Not rs.EOF
    Debug.Print rs!EmployeeName & " - " & rs!Salary
    rs.MoveNext
Loop

rs.Close
Set rs = Nothing
Set db = Nothing

This code prompts the user to enter a department and dynamically builds the SQL query to retrieve employees in that department.

5. Handling SQL Errors

Errors in SQL queries can arise from issues like syntax mistakes, incorrect table or column names, or other invalid operations. VBA provides several techniques for handling errors that may occur when executing SQL queries.

Example: Error Handling Using On Error

On Error GoTo ErrorHandler

DoCmd.RunSQL "UPDATE Employees SET Salary = 50000 WHERE EmployeeID = 1"

Exit Sub

ErrorHandler:
    MsgBox "An error occurred: " & Err.Description

In this example, the On Error GoTo ErrorHandler statement directs VBA to jump to the ErrorHandler label if an error occurs while executing the SQL query. The error message is then displayed in a message box.

Best Practices for Writing SQL Queries in VBA

  • Parameterize Queries: Avoid concatenating user input directly into SQL queries, as this can expose your application to SQL injection attacks. Use parameterized queries where possible.
  • Use DAO or ADO Recordsets for SELECT Queries: For SELECT queries that return data, use DAO or ADO recordsets for better handling of the result sets and for iterating through records.
  • Test Queries in Access: Before embedding SQL in VBA, test your queries directly in the Access query designer to ensure they return the expected results.
  • Handle Errors Gracefully: Always include error handling when executing SQL queries to catch and handle potential issues.

Conclusion

Writing SQL queries in VBA provides a powerful method for automating and managing data in Access. By leveraging the DoCmd object for action queries and DAO/ADO for retrieving and manipulating data, you can interact with the database programmatically. Dynamic SQL allows you to build flexible queries based on user input, and error handling ensures that your application runs smoothly even when issues arise. Mastering SQL in VBA is essential for building robust, data-driven applications in Access.

Commenting is not enabled on this course.