09-Microsoft-Access-VBA-Programming-eBook-SAMPLE
09-Microsoft-Access-VBA-Programming-eBook-SAMPLE
Thank you for your purchase and commitment to learn and master the tools and features of
Microsoft Access VBA Programming.
This comprehensive user guide covers the essential objects, techniques and concepts to get
you started in the best possible way that I know and have taught to my many students over
the years.
There are two ways you could use this reference guide. It can be used as a general reference
guide jumping between sections in any suitable order to fill any gaps in your knowledge and
establish an understanding as taught in my training courses or if you’re a complete new
beginner then simply start from the beginning and read the whole guide first and then go
over each section again applying the examples shown to help manage and build a database
application.
At first glance, learning about Microsoft Access VBA may be deemed quite a steep learning
curve but by using the examples and understanding the theories covered in this guide, I aim
to flatten that curve to the easiest and painless way possible.
At the end of day, it will require your investment of time, perseverance and having an open
and positive mindset as at times it may seem all too much to take in. If this happens, take a
break, go for a walk, do something else for a few hours and then revisit this at a later point.
All the examples used in this user guide can be tested with sample data which is available in
the box below:
Included with this user guide, I have attached a zip file containing three ACCDB database files and plenty
of TXT files too (containing some of the VBA code illustrated in this guide – saving the time to re-write
code). It’s recommended that you actually type the VBA code shown in this guide to fully consolidate and
understand the section being explained. Please review the file ‘Readme.txt’ when you have downloaded
and opened the zip file.
DISCLAIMER OF WARRANTIES/DAMAGES
All software data files is provided ”as-is,” without any express or implied warranty.
In no event shall the author be held liable for any damages arising from the use of this software.
The user must assume the entire risk of using the software.
Disclaimer
The information provided within this eBook is for general informational purposes only. While we try to keep
the information up-to-date and correct, there are no representations or warranties, express or implied, about
the completeness, accuracy, reliability, suitability or availability with respect to the information, products,
services, or related graphics contained in this eBook for any purpose. Any use of this information is at your
own risk.
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by
any means, electronic, mechanical, photocopying, recording, scanning or otherwise without the prior written
permission of the author Ben Beitler ([email protected]) or his company; Access Database
Tutorial © 2018 https://www.accessdatabasetutorial.com/
CONTENTS
INTRODUCTION ................................................................................................................. 1
VISUAL BASIC EDITOR (VBE WINDOW) ........................... ERROR! BOOKMARK NOT DEFINED.
References to Objects in VBA – What are they? .................................................. Error! Bookmark not defined.
How to set References to Object Libraries ........................................................... Error! Bookmark not defined.
How to use the Object Browser .......................................................................... Error! Bookmark not defined.
Storing data in variables and constants ............................................................... Error! Bookmark not defined.
Making logical decisions in VBA code .................................................................. Error! Bookmark not defined.
Repeating VBA code using Loops ........................................................................ Error! Bookmark not defined.
Using Do...Loop to loop through code ................................................................. Error! Bookmark not defined.
Using While...Wend to loop through code .......................................................... Error! Bookmark not defined.
Using For...Next to loop through code ................................................................ Error! Bookmark not defined.
Clarity between objects and collections .............................................................. Error! Bookmark not defined.
Understanding the properties and the methods.................................................. Error! Bookmark not defined.
Controlling and manipulating properties and methods ....................................... Error! Bookmark not defined.
VBA WORKING WITH ACCESS FORMS ............................ ERROR! BOOKMARK NOT DEFINED.
Enabling and disabling Form controls .................................................................. Error! Bookmark not defined.
Choosing an object and event for the code ......................................................... Error! Bookmark not defined.
Controlling boldface, italics, and other attributes ............................................... Error! Bookmark not defined.
Using the With...End With statements ................................................................ Error! Bookmark not defined.
Adding a related record to another table (via a Form) ......................................... Error! Bookmark not defined.
More DoCmd methods for forms ........................................................................ Error! Bookmark not defined.
WORKING WITH VBA, RECORDSETS & SQL ..................... ERROR! BOOKMARK NOT DEFINED.
You already know some SQL ............................................................................... Error! Bookmark not defined.
Writing SQL without knowing any SQL ................................................................ Error! Bookmark not defined.
Select queries versus Action queries ................................................................... Error! Bookmark not defined.
Getting SQL into Access VBA ............................................................................... Error! Bookmark not defined.
Hiding those unwanted warning messages ......................................................... Error! Bookmark not defined.
Creating a new, empty table using Access VBA ................................................... Error! Bookmark not defined.
Closing and deleting tables through VBA............................................................. Error! Bookmark not defined.
Updating and deleting records in a Table ............................................................ Error! Bookmark not defined.
Working with Select queries and Recordsets ....................................................... Error! Bookmark not defined.
Understanding and defining the recordset and data source ................................ Error! Bookmark not defined.
Filling the recordset with data ............................................................................ Error! Bookmark not defined.
Using For Each…Next loops with Controls ........................................................... Error! Bookmark not defined.
Tips on more conventions and reading code ....................................................... Error! Bookmark not defined.
VBA INTERFACING WITH THE REAL WORLD.................... ERROR! BOOKMARK NOT DEFINED.
Adding controls to the dialog box ....................................................................... Error! Bookmark not defined.
CUSTOMISING LISTS & DROP-DOWN MENUS ................. ERROR! BOOKMARK NOT DEFINED.
Using VBA for Combo and List Boxes ................................................................... Error! Bookmark not defined.
Listing field names .............................................................................................. Error! Bookmark not defined.
Giving users a quick find option .......................................................................... Error! Bookmark not defined.
CREATING YOUR OWN CUSTOM FUNCTIONS ................. ERROR! BOOKMARK NOT DEFINED.
TESTING AND DEBUGGING YOUR CODE ......................... ERROR! BOOKMARK NOT DEFINED.
Getting back to normal in the Code window ....................................................... Error! Bookmark not defined.
Wrestling runtime errors .................................................................................... Error! Bookmark not defined.
Client/Server Microsoft Access – Splitting the database ...................................... Error! Bookmark not defined.
Linking to external data using VBA code ............................................................. Error! Bookmark not defined.
Avoiding multiple tables and links (handing duplications) ................................... Error! Bookmark not defined.
VBA WITH OTHER OFFICE APPLICATIONS ....................... ERROR! BOOKMARK NOT DEFINED.
Away from Access, creating the Word template.................................................. Error! Bookmark not defined.
Writing VBA to send data to Word ...................................................................... Error! Bookmark not defined.
Example using a query and a form ...................................................................... Error! Bookmark not defined.
Writing the Excel VBA code ................................................................................. Error! Bookmark not defined.
Using the ADO SQL Recordset to Excel ................................................................ Error! Bookmark not defined.
CUSTOM FORM WIZARD TOOL (BONUS) ........................ ERROR! BOOKMARK NOT DEFINED.
Access Database Tutorial – Microsoft Access VBA Programming
Introduction
As you should be familiar with Microsoft Access, you will know how large and functionally
rich this relational database management system (RDBMS) is in offering the many ways to
manage data (information).
Whether MS Access is used for managing those mailing lists, memberships systems,
scientific and statistical data, an entire small business (SME) operation, or just about
anything else that involves the storing and managing of potentially large amounts of
information; at some point, to add any finishing touches to a usable and friendly-user
database creating a professional look and polished feel will require some level of
automation.
As this guide implies, Visual Basic for Applications (VBA) will be key here and serve you well
to enhance the power of your Microsoft Access database. It’s not a guide about creating
Access tables, queries, forms, reports, macros and such (please visit
https://accessdatabasetutorial.com/ebooks/microsoft-access-2016-ebook-offer/ for the
complete guide) but you will need a good base knowledge and understanding before
approaching and deploying VBA which this guide will assume you are ready for this next
step and stay focused on just Access VBA.
Furthermore, there’s really no point in even using VBA until you’ve already created a
database with at least some tables, maybe a few queries and forms added to it. In fact, as
you are now gathering, writing VBA code is usually the last step in creating a custom-built
Access database.
Many programming books and reference guides that you may have seen assumes you need
to be a programmer to fully immerse yourself here, this one doesn’t assume that! What I’m
saying is you don’t even have to be an accomplished programmer who is just picking up a
new programming language. Better still, I’m assuming that you’ve never written any
programming code in your life — and maybe you aren’t even all that sure what
programming code actually means or how it could even relate to Microsoft Access.
Hopefully, by the time you finish with this guide, you’ll know exactly what VBA is about and
you’ll know how it could and should fit into your Access database.
There’s going to be plenty of obscure terms that you’ll discover and master their meanings
as they are being bandied about in this guide like ‘code’, ‘variables’, ‘arrays’, ‘loops’,
‘objects’ and will after a while become common knowledge and a new language to you.
You’ll be able to write and use your own custom-built code, just like professional
programmers do – impressing others and even improving your CV along the way!
https://accessdatabasetutorial.com/
Access Database Tutorial – Microsoft Access VBA Programming
If you’re an absolute VBA beginner, please start at the beginning of this guide and following
the order presented here as I explain the essential detail in each section.
For experienced VBA users, you can probably start anywhere that looks interesting. If you
get in over your head at some point, perhaps take a step back and review the earlier
chapters where you can quickly fill in the knowledge gap that may be causing some
confusion.
You will note that there is no application version number in this guide or in its title –
meaning it’s not Access XP VBA, Access 2003 VBA, Access 2010 VBA or even Access 2016
VBA. This is because although there have been some changes and improvements to Access
with later releases, the VBA programming language has hardly changed over the many
years. In fact, the code that you see here should work well as-early as the release of Access
97 (last century) and also with Access 2000 too, and any subsequent versions released since.
https://accessdatabasetutorial.com/ 2
Access Database Tutorial – Microsoft Access VBA Programming
When you write text in a programming language style (as opposed to writing in plain pseudo
English), you’re writing code. Programmers use the term code to refer to anything that’s
written in a computer programming language.
For example, the illustration below shows some example VBA code. The whole trick to
learning VBA is learning what all the various words in the language mean so that you can
write code that tells MS Access exactly how to perform some task.
If the example code shown above looks like meaningless gibberish to you, that’s perfectly
normal and not to worry about it for now. Programming (or writing code) is a skill you have
to learn and is not a naturally style people adapt at first though reading part of the code
may make some sense. For now, it’s sufficient just to know what code looks like.
The key to good code is the ability to use the same code over and over again and help
automate those mundane tasks within Access (and beyond). For example, if you wanted to
convert or translate a real value (number) into words for a simple task of printing out a
cheque run:
i.e. £1,050.99 would translate into “One thousand and fifty pounds, 99 pence”.
https://accessdatabasetutorial.com/ 3
Access Database Tutorial – Microsoft Access VBA Programming
VBA code would be required to interrogate and process a returning value (in text) as there is
no standard function as shipped with MS Access.
In essence, MS Access does indeed provide a rich set of tools that lets you create a database
without any programming at all. You could easily spend many months or a few years just
learning all the possible things you can do with an Access database without writing any VBA
code. Yet despite the huge number of things you can do without programming, sometimes
you will want your database to accomplish some task that’s not built into Access. That’s
where VBA comes in. – it’s going to plug a gap!
When you’re writing VBA code or just looking at some VBA code, for example written by
someone else, the code is just a set of instructions that Access can perform at any time, over
and over again and when it’s executed (running the VBA code), it will impact the database in
some shape or form.
Consider the scenario where you command a child to “open the door.” Think about all the
individual actions that it takes to accomplish that one statement. The child has to approach
the door, align the hand with the door knob, move the hand and grasp it around the door
knob, and then twist and pull the door knob while swinging the arm in an arc motion.
We don’t have to command each specific step, and indeed life would be very tedious if we
constantly had to issue commands at such a micro level of detail. However, somewhere
along the line, the child had to learn what it meant and all the steps in the process to open a
door. The child didn’t have to be told for each step and probably figured it out by observing
others and by bumping into themselves a few times.
Therefore, to ask the computer to open the door is meaningless until you actually define the
exact steps required to accomplish the task. You can’t rely on the computer to observe and
understand the act of opening the door as a child would. Fortunately, you can build upon
the work done by other programmers. So, for example, when you want to display a little
message box saying, “Hello, World!” you can use a single line of code or instructions as
shown below. This combines programming done by others with something you want said.
https://accessdatabasetutorial.com/ 4
Access Database Tutorial – Microsoft Access VBA Programming
Behind the scenes, the instruction (command) MsgBox goes through several steps; it
instructs the computer how to draw the box, how to position it, what button to put on it,
and how to style it.
All of those details are abstracted away from us, which makes our task so much easier.
Knowing that the computer needs every step to be defined, you can appreciate the benefit
of being able to leverage existing programming and commands to write your own code. But
it’s still upon you to supply the missing pieces, like the actual message “Hello, World!”
Remembering the general rule that it can’t do what you didn’t tell it to do is invaluable in
programming.
When writing code, you are working with a type of program called a compiler, which is
responsible for translating the VBA language into machine language that the computer can
understand and execute. As you write code, the compiler provides feedback on whether
statements are valid and free of syntax errors (structural errors). When discussing how the
computer will react, we will often refer to the compiler or VBA Editor.
Note: The term object-oriented stems from the fact that everything you create in MS Access — a table, form, report, or
whatever — is considered an object.
The Navigation pane as shown below (or Database window for the earlier versions of MS
Access), is the main container in which you store all the main objects that make up a single
database file (typically ‘ACCDB’ or ‘MDB’ file).
https://accessdatabasetutorial.com/ 5
Access Database Tutorial – Microsoft Access VBA Programming
For the earlier versions, the left column of the Database window is the object list, and each
name in the list represents a type of object.
For the later versions, the groups of the Navigation pane are its object list, and each name in
the list represents a type of object, as summarised below.
Tables: Tables contain the raw data that all other object types display and manage. Data in
tables is stored in records (rows) and fields (columns).
Queries: Use queries to sort and filter data as well as define relationships among multiple
related tables.
https://accessdatabasetutorial.com/ 6
Access Database Tutorial – Microsoft Access VBA Programming
Forms: Access forms are similar to printed fill-in-the-blank forms, but they allow you to view
and change data stored in Access tables.
Reports: Reports are objects that define how data should be presented on printed reports.
Pages (dropped with later versions): Pages are similar to forms, but users can access data in
tables through a Web browser rather than directly through Access.
The Modules container, as you’ll soon discover, is one of the places where you store VBA
code. If you’re not already familiar with modules, that’s fine. Modules are what this guide is
really all about.
One of the most important things to understand is that you don’t use VBA “instead of”
other objects like tables and forms. You use VBA to enhance the capabilities of other object
types. Therefore, as already pointed out, it makes no sense to even try VBA until you have a
firm grasp of the purpose and capabilities of those other object types in an Access database.
So, as you now know, VBA code is stored in modules which is basically an electronic sheet of
paper or a text view on which VBA code is typed.
There are however two types of modules that can be found in Access – they are:
Standard module: A page that contains VBA code that’s accessible to all objects in the
database. This can be deemed as public and available from many objects.
Class module: A page of code that’s attached to every form and report you create. VBA code
in the class module is accessible only to the form or report to which the class module is
attached. This can be deemed as private to that object.
Class Module with sample VBA code and the design view of an Access Form
https://accessdatabasetutorial.com/ 7
Access Database Tutorial – Microsoft Access VBA Programming
To confirm then (and apologise for being a little repetitive but it’s important), the main
difference between a standard module and a class module is one of scope. VBA code in a
standard module has a global scope, which means that the code can be accessed by every
object in the database. A class module has a local scope, meaning that its code is accessible
only to one form or one report in the database.
We will be revisiting and expanding on scope later in this guide but for now, just park it to
one side!
2. Double-click the desired module node and you will be taken straight to the Window
view (VBA Editor) showing its content.
https://accessdatabasetutorial.com/ 8
Access Database Tutorial – Microsoft Access VBA Programming
VBA Editor Window – Three panes visible including VBA code for selected module (mod_General)
Of course, until you have created a module (covered later in this guide), this will remain
empty but for now you know how to open a standard module.
Note: You may discover that some objects in the Navigation pane may be hidden and appear not to exist. There are
‘Navigation Options’ in the Access database, Navigation pane to control such settings.
Also note that unlike the other objects, when you double-click this type of object, it will not
run or execute – only appear as a design-view ready for editing.
https://accessdatabasetutorial.com/ 9
Access Database Tutorial – Microsoft Access VBA Programming
1. Locate the object (form or report) where the class module will be found and choose
design-view (right-mouse click, choose ‘Design’).
2. In the design view, you can either display the ‘Property Sheet’ and then select a
control on the form or report which dynamically changes the property sheet’s view.
https://accessdatabasetutorial.com/ 10
Access Database Tutorial – Microsoft Access VBA Programming
4. Alternatively, to view the class module for the entire form or report, locate the
ribbon bar and under the ‘Design’ tab, locate the ‘View Code’ icon.
View Code icon to load the VBE Editor Window and navigate to the form’s class module
You now be looking at the VBA editor view with the active window of a class module of the
selected object (form or report).
Every form and report will have a Private class module associated to it and will self-generate
when the first stored procedure is required to be stored.
Note: When a stored procedure is created, a class module is attached to that object and has a private scope. At the same
time, a form or report has a property called ‘Has Module’ which is set to True when a stored procedure is created (these
defaults as False when a form or report is first created). By resetting this property back to False, will delete the associated
class module and its VBA code – a way to remove code quickly!
https://accessdatabasetutorial.com/ 11
Access Database Tutorial – Microsoft Access VBA Programming
TIP!
At any time and any point when working within the MS Access environment (interface), you
can use the keyboard shortcut of ALT + F11 which will toggle between the Visual Basic
Editor (VBE Window) and MS Access.
Alternatively, locating the Visual Basic icon on the ‘Database Tools’ tab of the ribbon bar
will switch you to the VBE Window.
Ribbon Bar, Database Tools tab, Visual Basic icon to load the VBE Editor Window
Did you know that your database may already contain some VBA code?
As you have taken the time and carefully created your database and then utilised the built-
in Control Wizards to add for example a Command Button with one of the defined actions
like opening another form or a report, you have in fact generated VBA code and the code
can be found in its class module.
Note: With the later versions of Access (Access 2010 onwards), this has reverted back to using Embedded Macros providing
the same actions.
Therefore, a VBA procedure is a series of instructions written in VBA code that instructs an
application (like MS Access) exactly how to perform a specific task. In VBA code, each step in
the procedure is a single line of code (of execution). When Access executes a VBA
procedure, it does so step-by-step, from the top down. Access does whatever the first
statement tells it to do. Then it does whatever the second statement tells it to do, and so
forth, until it gets to the end of the procedure.
https://accessdatabasetutorial.com/ 12
Access Database Tutorial – Microsoft Access VBA Programming
Exactly when Access executes a procedure is entirely up to where you place and apply the
call. Typically, you want to tie the procedure to some event that happens on screen. For
example, you might want the procedure to do its task as soon as someone clicks a command
button (in a form). Or perhaps you want your procedure to do its thing when-ever someone
types a value into a field, in a form. The action of where and when VBA code is executed (as
attached to a control or object) is the known as the event at which the code runs.
When this event to which you have attached your coded procedure occurs, MS Access calls
the procedure and that really means that Access does exactly what the VBA code in the
procedure tells it to do, in that order.
An example of an event, such as clicking a button (event: On Click) will call a procedure.
Access will execute the first line in the calling procedure; then it executes the second line in
the procedure, and so on.
When Access encounters the end of the procedure (which will be either End Sub or End
Function), it just stops executing code and returns to its normal state.
Take a look at this image below to follow the VBA code example line by line – don’t worry
about the actual keywords for now:
1
2
3
4
5
6
7
8
VBA code example of a Private procedure
1. The event is called by the command button’s Click event (cmdOpenMsg – a named
Command Button control on a Form) using the keyword Sub. The keyword Private
just makes this procedure a local procedure and hidden from other objects.
https://accessdatabasetutorial.com/ 13
Access Database Tutorial – Microsoft Access VBA Programming
3. A logical test known as an If test (covered later in this guide) has its own block (until
line 7). This line tests to see logically which button was clicked. A button’s value is
unique where the value 6 = ‘Yes’ and 7 = ‘No’ (there are returning values too). The
variable MyResponse temporarily holds the value returned (either a 6 or 7) before
the next line is executed. The green text are just comments and do not get executed
(good for explaining code!).
5. The keyword Else is a pivot point between the above line and line 6 that follows.
Therefore, only one line (line 4 or 6) will execute as the next line is the False side of
an If test.
7. This is the end of the If test block (End If). The next line of code (if any) would
continue.
All procedures will start with either Sub or Function and end with End Sub or End
Function respectively.
Hopefully, this made some sense to the order of how code is executed. The logical If test
will be covered in more detail later along with variables and other useful VBA keywords.
The highlighted blue text used was deliberate to emphasise these are VBA keywords and
reserved from the VBA library of keywords.
https://accessdatabasetutorial.com/ 14
Access Database Tutorial – Microsoft Access VBA Programming
TIP!
The example above code used indentations to help make it clearer to follow and does not
affect the execution of each line. In essence, all code could be left-aligned however, as you
write more complex procedures and lengthy code blocks, this convention will serve you
well!
There are two types of procedures in VBA. One type is the more commonly known as the
Sub procedure. A Sub procedure is always contained within a pair of Sub...End Sub
statements as shown:
Sub subName(...)
End Sub
The subName part of the example is the name of the procedure. The (...) part after the
name could be empty parentheses or a list of parameters and datatypes (also known as
arguments and covered later in this guide). The …[ VBA code here] stands for one or
more lines of VBA code.
When looking at code that’s already been written, you’ll see that some Sub procedures
have the word Public or Private to the left of the word Sub, as shown in these
examples:
Private Sub subName(...)
End Sub
End Sub
As already stated, Public or Private defines the scope of the procedure where a Public
procedure has the global scope (available to all other objects). Private procedures are
local and is visible to only the procedure in which it’s defined. Neither is particularly
important right now. All that is needed for now is that a Sub procedure is a chunk of VBA
code that starts with Sub or Private Sub or Public Sub statement and ends at the End
Sub statement.
https://accessdatabasetutorial.com/ 15
Access Database Tutorial – Microsoft Access VBA Programming
The second type of procedure that you can create in MS Access is a what is known as a
Function procedure. Unlike a Sub procedure, which performs a task, a Function
procedure generally does some sort of calculation and then returns the result of that
calculation.
The first line of a Function procedure starts with the word Function (optionally as
Private Function or Public Function) followed by its name. The last line of a
Function procedure ends with End Function as shown below:
Function functionName(...)
End Function
The functionName = …[the result] is normally the last line that pulls the answer out
of the procedure into where it’s being called (more on this later in this guide).
Because each procedure has its own calling signature and ends with either an End Sub or
End Function block, you can store many procedures in one module. Each procedure break
will have a dividing hard line between them to make it easier to read.
Note: If you leave out either the Public or Private keywords in your procedures, the default will be set as Public.
https://accessdatabasetutorial.com/ 16
Access Database Tutorial – Microsoft Access VBA Programming
We’d love to hear your comments about this guide, so if you would rather email us rather
than blogging, send your comments to [email protected] – and don’t forget that
my website has lots more articles and free videos to help you plan, build and implement an
Access database.
https://accessdatabasetutorial.com/ 17