Introduction to VBA in MS Access
Introduction to VBA in MS Access
What is VBA?
VBA (Visual Basic for Applications) is a programming language developed by Microsoft that is
used to automate tasks and create custom solutions within Microsoft Office applications, such as
Excel, Access, Word, Outlook, and PowerPoint.
VBA allows users to automate repetitive tasks, manipulate data, and create custom forms,
reports, and interfaces. It enables developers to write custom macros that extend the functionality
of Office applications, making them more powerful and efficient.
How to open the VBA Editor (VBE), Understanding VBA Basics, Variables and Data Types, Declaring
and using variables, Constants and scope, Writing Your First VBA Code, Message boxes (MsgBox) and
input boxes (InputBox), Simple procedures and functions, Control Structures in VBA, Conditional
statements (If...Then...Else, Select Case), Loops (For...Next, While...Wend, Do...Loop), Working with
Forms and Controls, Accessing form controls with VBA, Handling form events (OnClick, OnLoad,
OnCurrent), Intermediate Level, Working with Recordsets, DAO vs ADO, Opening, reading, and
modifying records, Adding, updating, and deleting records, Error Handling in VBA, Using On Error
Resume Next, Debugging techniques (Debug.Print, breakpoints, stepping through code), Working with
Queries and SQL in VBA, Running SQL queries using VBA (DoCmd.RunSQL, CurrentDb.Execute),
Parameterized queries, Automating Reports and Forms, Opening and filtering reports with VBA,
Modifying report properties dynamically, Handling User Input and Validations, Input validation with
VBA, Creating custom dialog boxes, Creating Custom Functions and Libraries, Writing reusable
functions, Creating and using class modules, Working with External Data, Importing/exporting data
using VBA, Connecting to Excel and Outlook, Building Complex Applications, Automating workflows,
Creating dynamic user interfaces, Security and Performance Optimization, Protecting VBA code,
Optimizing database performance, Deploying an Access Application, Creating an ACCDE file, Handling
multi-user environments
1. Variables in VBA
Declaring Variables
Assigning Values
myName = "Alex"
myAge = 24
mySalary = 50000.5
isActive = True
Sub ShowVariables()
message = "Name: " & myName & vbNewLine & "Age: " & myAge
End Sub
2. Functions in VBA
Creating a Function
End Function
Calling a Function
Sub TestFunction()
End Sub
3. Conditional Statements
IF...THEN...ELSE
vba
Copy
Edit
Sub CheckAge()
Else
End If
End Sub
SELECT CASE
vba
Copy
Edit
Sub CheckGrade()
Case Is >= 80
Case 70 To 79
MsgBox "Grade: B", vbInformation, "Result"
Case 60 To 69
Case Else
End Select
End Sub
4. Loops
For Loop
vba
Copy
Edit
Sub CountToTen()
Dim i As Integer
For i = 1 To 10
Next i
End Sub
While Loop
vba
Copy
Edit
Sub WhileLoopExample()
Dim x As Integer
x=1
While x <= 5
x=x+1
Wend
End Sub
Do Until Loop
vba
Copy
Edit
Sub DoUntilExample()
Dim y As Integer
y=1
Do Until y > 5
y=y+1
Loop
End Sub
5. Arrays in VBA
vba
Copy
Edit
Sub ArrayExample()
fruits(0) = "Apple"
fruits(1) = "Banana"
fruits(2) = "Cherry"
End Sub
vba
Copy
Edit
Sub LoopThroughArray()
Dim i As Integer
colors(0) = "Red"
colors(1) = "Green"
colors(2) = "Blue"
For i = 0 To 2
Next i
End Sub
6. Opening Forms
Open a Form
vba
Copy
Edit
Sub OpenMyForm()
End Sub
vba
Copy
Edit
Sub OpenFilteredForm()
End Sub
7. Opening a Table
vba
Copy
Edit
Sub OpenTable()
End Sub
8. Message Boxes
vba
Copy
Edit
Sub ShowMessage()
End Sub
vba
Copy
Edit
Sub ConfirmAction()
Else
End If
End Sub
Input Box
vba
Copy
Edit
Sub GetUserName()
Else
End If
End Sub
🚀 Next Steps
Automating reports
ChatGPT said:
In VBA, vbInformation and vbCritical are built-in constants used in message boxes (MsgBox) to define
the type of icon that appears in the dialog.
1. vbInformation
Example:
vba
Copy
Edit
2. vbCritical
Example:
vba
Copy
Edit
You said:
if with null
ChatGPT said:
In VBA, you can check if a value is Null using the IsNull() function. This is useful when dealing with
database fields, textboxes, or variables that may not have a value.
vba
Copy
Edit
Sub CheckForNull()
If IsNull(myValue) Then
Else
End If
End Sub
Wrong: If myValue = Null Then → This will always return False, because Null is not a value but an
absence of value.
vba
Copy
Edit
Sub CheckTextBox()
Else
End If
End Sub
IsNull(Me.txtName): Handles cases where the textbox has never been filled.
Me.txtName.Value = "": Handles cases where the textbox is empty (erased by the user).
vba
Copy
Edit
Sub CheckTableField()
Dim rs As DAO.Recordset
If IsNull(rs!LastName) Then
Else
End If
End If
rs.Close
Set rs = Nothing
End Sub
Instead of checking IsNull(), you can use Nz() to replace Null with a default value:
vba
Copy
Edit
Summary
You said:
ChatGPT said:
1. Or (Logical OR)
Example:
vba
Copy
Edit
Sub TestOr()
Dim x As Integer
x=5
If x = 5 Or x = 10 Then
End If
End Sub
Example:
vba
Copy
Edit
Sub TestAnd()
Dim x As Integer
x=5
End If
End Sub
✅ Output: "Number is between 1 and 9" (because x > 0 and x < 10 are both True).
Example:
vba
Copy
Edit
Sub TestConcatenation()
firstName = "Alex"
lastName = "Makoha"
MsgBox "Full Name: " & firstName & " " & lastName, vbInformation, "Concatenation"
End Sub
Summary of Differences
And Logical AND (Both True) If x > 0 And x < 10 Then True if x is between 1-9
VBA (Visual Basic for Applications) is a programming language used to automate tasks
in Microsoft Access.
vba
CopyEdit
Sub HelloWorld()
MsgBox "Hello, VBA in MS Access!"
End Sub
vba
CopyEdit
Sub ChangeLabel()
Forms("Form1").Controls("Label1").Caption = "Welcome to VBA!"
End Sub
vba
CopyEdit
Private Sub cmdClickMe_Click()
MsgBox "You clicked the button!", vbInformation, "Button Click"
End Sub
vba
CopyEdit
Dim studentName As String
Dim age As Integer
Dim price As Double
Dim isRegistered As Boolean
3.2 Using Variables
vba
CopyEdit
Sub ShowStudent()
Dim studentName As String
studentName = "Alex Makoha"
MsgBox "Student Name: " & studentName
End Sub
4.1 If Statements
vba
CopyEdit
Sub CheckAge()
Dim age As Integer
age = 20
If age >= 18 Then
MsgBox "You are an adult."
Else
MsgBox "You are a minor."
End If
End Sub
vba
CopyEdit
Sub CountToTen()
Dim i As Integer
For i = 1 To 10
Debug.Print i
Next i
End Sub
vba
CopyEdit
Sub WhileLoopExample()
Dim i As Integer
i = 1
While i <= 5
Debug.Print "Iteration: " & i
i = i + 1
Wend
End Sub
vba
CopyEdit
Sub InsertRecord()
Dim db As DAO.Database
Dim sql As String
Set db = CurrentDb
sql = "INSERT INTO Students (StudentName, Age) VALUES ('John Doe', 25)"
db.Execute sql, dbFailOnError
MsgBox "Record Inserted!"
End Sub
vba
CopyEdit
Sub UpdateRecord()
Dim db As DAO.Database
Set db = CurrentDb
db.Execute "UPDATE Students SET Age = 30 WHERE StudentName = 'John Doe'"
MsgBox "Record Updated!"
End Sub
vba
CopyEdit
Sub DeleteRecord()
Dim db As DAO.Database
Set db = CurrentDb
db.Execute "DELETE FROM Students WHERE StudentName = 'John Doe'"
MsgBox "Record Deleted!"
End Sub
vba
CopyEdit
Sub RetrieveRecords()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM Students")
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
Module 6: Handling User Input with Forms
vba
CopyEdit
Sub GetTextBoxValue()
Dim userInput As String
userInput = Forms("Form1").Controls("txtName").Value
MsgBox "You entered: " & userInput
End Sub
vba
CopyEdit
Sub SaveUserInput()
Dim db As DAO.Database
Dim sql As String
Dim userName As String
userName = Forms("Form1").Controls("txtName").Value
Set db = CurrentDb
sql = "INSERT INTO Users (UserName) VALUES ('" & userName & "')"
db.Execute sql, dbFailOnError
MsgBox "User Saved!"
End Sub
vba
CopyEdit
Sub OpenReport()
DoCmd.OpenReport "Report1", acViewPreview
End Sub
vba
CopyEdit
Sub ExportReportPDF()
DoCmd.OutputTo acOutputReport, "Report1", acFormatPDF,
"C:\Reports\MyReport.pdf"
MsgBox "Report exported successfully!"
End Sub
Module 8: Error Handling
vba
CopyEdit
Sub ErrorHandlingExample()
On Error GoTo ErrorHandler
Dim x As Integer
x = 10 / 0 ' This will cause an error
Exit Sub
ErrorHandler:
MsgBox "An error occurred: " & Err.Description, vbCritical, "Error"
End Sub
vba
CopyEdit
Sub OpenForm()
DoCmd.OpenForm "Form1"
End Sub
vba
CopyEdit
Sub SendEmail()
DoCmd.SendObject acSendNoObject, , , "[email protected]", , , "Test
Subject", "This is a test email.", False
End Sub
txtStudentName
txtAge
btnSave
btnDelete
lstStudents (ListBox to display records)
Forms("Form1").lstStudents.RowSource = ""
While Not rs.EOF
Forms("Form1").lstStudents.AddItem rs!StudentName & ";" & rs!Age
rs.MoveNext
Wend
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
This course provides a solid foundation for VBA in MS Access. Let me know if you need
additional explanations or custom VBA codes! 🚀
4o
You said:
Data
Size Description Example
Type
Byte 1 byte Stores numbers from 0 to 255 Dim x As Byte
Integer 2 bytes Stores whole numbers from -32,768 to 32,767 Dim x As Integer
Long
Stores large whole numbers from -2,147,483,648 to Dim x As Long
4 bytes
2,147,483,647
Single
Stores floating-point numbers with 7 digits of Dim x As Single
4 bytes
precision
Double
Stores floating-point numbers with 15 digits of Dim x As Double
8 bytes
precision
Currency 8 bytes Stores monetary values with 4 decimal places Dim x As Currency
Decimal
12 Stores up to 28 decimal places (must be declared Dim x As Variant
bytes via Variant)
String Varies Stores text data (up to 2 billion characters) Dim name As String
Boolean 2 bytes Stores True or False Dim flag As Boolean
Date 8 bytes Stores dates and times Dim d As Date
Dim db As
Object 4 bytes Stores references to objects DAO.Database
Variant
Can hold any data type (not recommended for Dim x As Variant
Varies
performance)
Example
vba
CopyEdit
Sub ArithmeticExample()
Dim a As Integer, b As Integer
a = 10
b = 3
MsgBox "Addition: " & (a + b) & vbNewLine & _
"Subtraction: " & (a - b) & vbNewLine & _
"Multiplication: " & (a * b) & vbNewLine & _
"Division: " & (a / b) & vbNewLine & _
"Integer Division: " & (a \ b) & vbNewLine & _
"Modulus: " & (a Mod b) & vbNewLine & _
"Power: " & (a ^ 2)
End Sub
Example
vba
CopyEdit
Sub ComparisonExample()
Dim x As Integer, y As Integer
x = 10
y = 5
MsgBox "Equal: " & (x = y) & vbNewLine & _
"Not Equal: " & (x <> y) & vbNewLine & _
"Greater: " & (x > y) & vbNewLine & _
"Less: " & (x < y) & vbNewLine & _
"Greater or Equal: " & (x >= y) & vbNewLine & _
"Less or Equal: " & (x <= y)
End Sub
Example
vba
CopyEdit
Sub LogicalExample()
Dim a As Boolean, b As Boolean
a = True
b = False
MsgBox "And: " & (a And b) & vbNewLine & _
"Or: " & (a Or b) & vbNewLine & _
"Not A: " & Not a & vbNewLine & _
"Xor: " & (a Xor b)
End Sub
2.4 String Concatenation Operator
Example
vba
CopyEdit
Sub StringConcat()
Dim firstName As String, lastName As String
firstName = "Alex"
lastName = "Makoha"
MsgBox "Full Name: " & firstName & " " & lastName
End Sub
Example
vba
CopyEdit
Sub AssignmentExample()
Dim num As Integer
num = 100
MsgBox "Value of num: " & num
End Sub
Conclusion
This guide covers all data types and operators in VBA for MS Access with examples. Let me
know if you need further clarification or advanced examples! 🚀
Let's say we have a form named "frmLogin" with the following controls:
UserID (AutoNumber)
FullName (Text)
Email (Text)
Form Controls
Explanation
Explanation
userID = Me.txtUserID.Value
6. Updating a Record
Users can update records in the database using VBA.
VBA Code
vba
CopyEdit
Private Sub btnUpdate_Click()
Dim db As DAO.Database
Dim sqlQuery As String
Dim userID As Integer
userID = Me.txtUserID.Value
Explanation
Let me know! 🚀
4o
You said:
Example
vba
CopyEdit
MsgBox Me.txtUsername.Value
Output: "Alex"
2. Why Use Me?
Me is a shortcut that refers to the current form. Instead of writing:
vba
CopyEdit
Forms!frmLogin.txtUsername.Value
vba
CopyEdit
Me.txtUsername.Value
Reading a Value
vba
CopyEdit
Dim user As String
user = Me.txtUsername.Value
MsgBox "Hello, " & user
If the user entered "Alex", the message box will display: "Hello, Alex"
Setting a Value
vba
CopyEdit
Me.txtUsername.Value = "Admin"
4. Alternative to .Value
.Value is optional when referring to textboxes in MS Access. The following two statements are
the same:
vba
CopyEdit
Me.txtUsername.Value ' Explicit reference
Me.txtUsername ' Default property
vba
CopyEdit
MsgBox Me.txtUsername
MsgBox Me.txtUsername.Value
Explanation
Conclusion
Me refers to the current form.
.txtUsername refers to a textbox on the form.
.Value retrieves or sets the content of the textbox.
.Value is optional when reading but required when writing.
Would you like more examples on using form controls with VBA? 🚀
4o
You said:
Here’s how to create a simple Login and Registration Form in MS Access using VBA.
Steps to follow:
vba
CopyEdit
Private Sub btnLogin_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim username As String
Dim password As String
Explanation:
The code checks if the username and password match the records in the tblUsers table.
If the credentials are valid, a success message appears; otherwise, an error message is
shown.
Steps to follow:
1. Design the Form (frmRegister):
o Add txtUsername, txtPassword, txtConfirmPassword, btnRegister, and
lblMessage.
2. VBA Code for Registration:
vba
CopyEdit
Private Sub btnRegister_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim username As String
Dim password As String
Dim confirmPassword As String
After successful login, you can navigate to other forms. For example, after the user
successfully logs in, you can open a main dashboard form:
vba
CopyEdit
DoCmd.OpenForm "frmDashboard"
For registration, after the successful registration, you might redirect the user to the login
form:
vba
CopyEdit
DoCmd.OpenForm "frmLogin"
Final Thoughts