welcome to microsoft access vba - access database tutorial

26

Upload: others

Post on 25-Oct-2021

40 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Welcome to Microsoft Access VBA - Access Database Tutorial
Page 2: Welcome to Microsoft Access VBA - Access Database Tutorial

Welcome to Microsoft Access VBA

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.

It will sink in, I promise!

All the examples used in this user guide can be tested with sample data which is available in the box below:

SAMPLE FILES - FREE TO DOWNLOAD

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.

Access VBA Sample Files (URL link removed for this Sample)

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.

PLEASE DO NOT DOWNLOAD UNLESS YOU HAVE AGREED TO THIS DISCLAIMER.

Page 3: Welcome to Microsoft Access VBA - Access Database Tutorial

I hope you find this user guide of value and welcome your feedback comments - on ways this user manual could be improved or if you wish to get in contact with me, please do so at [email protected]

Once again, many thanks for your commitment – enjoy!

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. DATABASE FILES - 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. PLEASE DO NOT DOWNLOAD UNLESS YOU HAVE AGREED TO THIS DISCLAIMER. 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; AccessDatabase Tutorial © 2018 https://www.accessdatabasetutorial.com/

Page 4: Welcome to Microsoft Access VBA - Access Database Tutorial

CONTENTS

INTRODUCTION ................................................................................................................. 1

INTRODUCTION TO VBA PROGRAMMING .......................................................................... 3

The mindset of the VBA programmer ............................................................................................................. 4

Where does Access VBA code reside? ............................................................................................................ 5

Opening a standard module ........................................................................................................................... 8

Opening a class module ............................................................................................................................... 10

VBA procedures – What’s inside the modules .............................................................................................. 12

VISUAL BASIC EDITOR (VBE WINDOW) ........................... ERROR! BOOKMARK NOT DEFINED.

The Project Explorer ........................................................................................... Error! Bookmark not defined.

The Properties window ....................................................................................... Error! Bookmark not defined.

The Immediate window ...................................................................................... Error! Bookmark not defined.

The Code 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.

Searching the Object Library ............................................................................... Error! Bookmark not defined.

A SIMPLE VBA PROGRAM – TO START ............................ ERROR! BOOKMARK NOT DEFINED.

Creating a Standard Module ............................................................................... Error! Bookmark not defined.

Understanding Syntax (the structure) ................................................................. Error! Bookmark not defined.

Getting keyword help ......................................................................................... Error! Bookmark not defined.

Help with arguments .......................................................................................... Error! Bookmark not defined.

About named arguments .................................................................................... Error! Bookmark not defined.

Modifying Existing Code ...................................................................................... Error! Bookmark not defined.

Copy-and-paste code from the Web .................................................................... Error! Bookmark not defined.

Page 5: Welcome to Microsoft Access VBA - Access Database Tutorial

Importing standard modules ............................................................................... Error! Bookmark not defined.

Exporting standard modules ............................................................................... Error! Bookmark not defined.

UNDERSTANDING VBA CODE ......................................... ERROR! BOOKMARK NOT DEFINED.

Commenting your code ....................................................................................... Error! Bookmark not defined.

Understanding VBA Data Types .......................................................................... Error! Bookmark not defined.

Passing data to procedures ................................................................................. Error! Bookmark not defined.

Storing data in variables and constants ............................................................... Error! Bookmark not defined.

Storing data in arrays .......................................................................................... Error! Bookmark not defined.

Module-level versus procedure-level - scope ...................................................... Error! Bookmark not defined.

Naming conventions for variables ....................................................................... Error! Bookmark not defined.

Making logical decisions in VBA code .................................................................. Error! Bookmark not defined.

Using If...End If statements ................................................................................. Error! Bookmark not defined.

Using a Select Case block .................................................................................... 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.

USING ACCESS WITH VBA .............................................. ERROR! BOOKMARK NOT DEFINED.

Understanding the object models ....................................................................... 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.

Working with class procedures ........................................................................... Error! Bookmark not defined.

Enabling and disabling Form controls .................................................................. Error! Bookmark not defined.

Using VBA to position the cursor ......................................................................... Error! Bookmark not defined.

Page 6: Welcome to Microsoft Access VBA - Access Database Tutorial

Square brackets and field names ........................................................................ Error! Bookmark not defined.

Choosing an object and event for the code ......................................................... Error! Bookmark not defined.

Saving the procedure .......................................................................................... Error! Bookmark not defined.

Showing and hiding controls ............................................................................... Error! Bookmark not defined.

Making controls read-only .................................................................................. Error! Bookmark not defined.

Responding to Form Events ................................................................................ Error! Bookmark not defined.

Changing the appearance of objects ................................................................... Error! Bookmark not defined.

Changing colours ................................................................................................ Error! Bookmark not defined.

Controlling boldface, italics, and other attributes ............................................... Error! Bookmark not defined.

Changing special effects ...................................................................................... Error! Bookmark not defined.

Using the With...End With statements ................................................................ Error! Bookmark not defined.

Populating data to form controls ........................................................................ Error! Bookmark not defined.

Opening and closing Forms ................................................................................. Error! Bookmark not defined.

Closing a form ..................................................................................................... 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.

Storing SQL statements in variables .................................................................... 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.

Adding records to a Table ................................................................................... Error! Bookmark not defined.

Page 7: Welcome to Microsoft Access VBA - Access Database Tutorial

Appending a single record with SQL .................................................................... 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 a connection ........................................................... 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.

Methods for managing recordsets ...................................................................... Error! Bookmark not defined.

Referring to fields in a recordset ......................................................................... Error! Bookmark not defined.

Closing Recordsets and Collections ..................................................................... Error! Bookmark not defined.

MORE ON & WORKING WITH RECORDSETS .................... ERROR! BOOKMARK NOT DEFINED.

Looping through Collections ............................................................................... Error! Bookmark not defined.

Using For Each…Next loops with Controls ........................................................... Error! Bookmark not defined.

Using shorter names for objects .......................................................................... Error! Bookmark not defined.

Tips on more conventions and reading code ....................................................... Error! Bookmark not defined.

Print Multiple Invoices utility .............................................................................. Error! Bookmark not defined.

VBA INTERFACING WITH THE REAL WORLD .................... ERROR! BOOKMARK NOT DEFINED.

Creating your own Dialog Boxes .......................................................................... Error! Bookmark not defined.

Displaying and Responding to Messages ............................................................. Error! Bookmark not defined.

Responding to a MsgBox button click .................................................................. Error! Bookmark not defined.

Converting Forms to dialog boxes ....................................................................... Error! Bookmark not defined.

Storing Dialog Box settings ................................................................................. Error! Bookmark not defined.

Setting form properties ....................................................................................... Error! Bookmark not defined.

Adding controls to the dialog box ....................................................................... Error! Bookmark not defined.

Detecting a Right-Click ........................................................................................ Error! Bookmark not defined.

CUSTOMISING LISTS & DROP-DOWN MENUS ................. ERROR! BOOKMARK NOT DEFINED.

Using VBA for Combo and List Boxes ................................................................... Error! Bookmark not defined.

Page 8: Welcome to Microsoft Access VBA - Access Database Tutorial

Listing field names .............................................................................................. Error! Bookmark not defined.

Listing text options ............................................................................................. Error! Bookmark not defined.

Listing table/query field values ........................................................................... Error! Bookmark not defined.

Linking between lists .......................................................................................... Error! Bookmark not defined.

Linking lists across forms .................................................................................... Error! Bookmark not defined.

Seeing whether a form is open ............................................................................ Error! Bookmark not defined.

Getting forms in sync .......................................................................................... Error! Bookmark not defined.

Giving users a quick find option .......................................................................... Error! Bookmark not defined.

CREATING YOUR OWN CUSTOM FUNCTIONS ................. ERROR! BOOKMARK NOT DEFINED.

The role of functions in VBA ................................................................................ Error! Bookmark not defined.

Creating your own functions ............................................................................... Error! Bookmark not defined.

Passing data to a function ................................................................................... Error! Bookmark not defined.

Returning a value from a function ....................................................................... Error! Bookmark not defined.

Testing a custom function ................................................................................... Error! Bookmark not defined.

Expanding on the GrossTotal function ................................................................. Error! Bookmark not defined.

A Proper Case (PCase) Function .......................................................................... Error! Bookmark not defined.

TESTING AND DEBUGGING YOUR CODE ......................... ERROR! BOOKMARK NOT DEFINED.

Understanding compilation and runtime ............................................................ Error! Bookmark not defined.

Considering types of program errors ................................................................... Error! Bookmark not defined.

Handling compile errors ...................................................................................... Error! Bookmark not defined.

Dealing with logical errors .................................................................................. Error! Bookmark not defined.

Checking on variables with Debug.Print .............................................................. Error! Bookmark not defined.

Slowing down code ............................................................................................. Error! Bookmark not defined.

Using the Locals window ..................................................................................... Error! Bookmark not defined.

Stepping through code in step mode ................................................................... Error! Bookmark not defined.

Getting back to normal in the Code window ....................................................... Error! Bookmark not defined.

Page 9: Welcome to Microsoft Access VBA - Access Database Tutorial

Wrestling runtime errors .................................................................................... Error! Bookmark not defined.

Responding to a runtime error ............................................................................ Error! Bookmark not defined.

Trapping runtime errors ...................................................................................... Error! Bookmark not defined.

VBA BEYOND MICROSOFT ACCESS ................................. ERROR! BOOKMARK NOT DEFINED.

Client/Server Microsoft Access – Splitting the database ...................................... Error! Bookmark not defined.

Importing from external databases ..................................................................... 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.

Creating Recordsets from external tables ............................................................ Error! Bookmark not defined.

Importing/Exporting/Linking to anything else ..................................................... Error! Bookmark not defined.

VBA WITH OTHER OFFICE APPLICATIONS ....................... ERROR! BOOKMARK NOT DEFINED.

Accessing the Object Library ............................................................................... Error! Bookmark not defined.

Exploring a program’s object model .................................................................... Error! Bookmark not defined.

Introducing the Application object ...................................................................... Error! Bookmark not defined.

Connecting to other programs ............................................................................ Error! Bookmark not defined.

Sending E-mail via Outlook ................................................................................. Error! Bookmark not defined.

Sending Data to Microsoft Word ......................................................................... Error! Bookmark not defined.

Away from Access, creating the Word template .................................................. Error! Bookmark not defined.

Creating my Access form ..................................................................................... Error! Bookmark not defined.

Writing VBA to send data to Word ...................................................................... Error! Bookmark not defined.

Interacting with Microsoft Excel ......................................................................... 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.

Page 10: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/

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!

Page 11: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 2

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.

One final note before we start…

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.

I will be using Microsoft Access 2016 (Office 365)

Page 12: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 3

Introduction to VBA Programming Visual Basic is a programming language — a language for writing instructions that a computer can read and process. VBA is a programming language that’s specifically designed to work with the application programs in Microsoft Office including the likes of Word, Excel, Outlook, and of course, Microsoft Access.

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”.

VBA code procedure example from a module (VBE editor)

Page 13: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 4

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.

The mindset of the VBA programmer We need to start by establishing a frame of reference as to what we should expect when we are writing VBA code.

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.

When working on a computer, it is helpful to remember that computers have to be instructed, basically shown the way on how you want it to do things. Be clear, the first thing to remember about computers is that they can’t do what you didn’t tell them to do.

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.

Page 14: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 5

MsgBox “Hello, World!”

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.

Where does Access VBA code reside? As you should know, Access is part of the Microsoft Office suite of applications and is a huge relational database management system (RDBMS) that you work by using modern object-oriented methods.

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).

VBA MsgBox Statement – “Hello Word!”

Page 15: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 6

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.

Access 2003 Database Window

Access 2016 Navigation Pane

Page 16: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 7

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.

Macros: Macros provide a means of automating certain aspects of Access without programming.

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

Page 17: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 8

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!

Opening a standard module As you now know, a standard module resides in the Navigation pane which is where you store the general and public scoped procedures for your database.

The steps couldn’t be any easier.

1. Expand the ‘Modules’ group to display all public standard modules:

2. Double-click the desired module node and you will be taken straight to the Window view (VBA Editor) showing its content.

Access Navigation Pane showing a module present

Page 18: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 9

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.

You can also right-mouse click to view sub-menu options too.

VBA Editor Window – Three panes visible including VBA code for selected module (mod_General)

Popup sub-menu (right mouse clicking action) for selected object

Page 19: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 10

Opening a class module This type of module can only be seen via another object namely a form or report and therefore you will need to first open the said object in its design-view (and not to run or execute the object).

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.

3. Under the ‘Events’ tab on the ‘Property Sheet’, you will see events which will mainly be blank but where there’s an event procedure to be opened will allow you to view the VBA code associated to the selected control.

Property Sheet – Access Form design view

Property Sheet – Event tab, On Click property for a command button

Page 20: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 11

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.

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!

View Code icon to load the VBE Editor Window and navigate to the form’s class module

VBE Editor Window – form’s class module VBA code shown

Page 21: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 12

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.

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.

VBA procedures – What’s inside the modules All VBA code will be found somewhere in the Visual Basic Editor (VBE Window) containing one or more procedures which really mimics and reflects the processes used in everyday language to perform a series of steps in order to achieve some goal. For example, the procedure of getting to work every morning requires a certain series of steps. The same definition holds true for VBA code. A procedure is a series of steps carried out in a specific order to achieve some desired result.

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.

Ribbon Bar, Database Tools tab, Visual Basic icon to load the VBE Editor Window

Page 22: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 13

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. 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.

2. MyResponse (known as a variable and covered later in this guide) waits for the returning value of the keyword MsgBox (stands for a pop-up ‘Message Box’) showing two buttons; ‘Yes’ and ‘No’ waiting for the user to click one of these buttons before it continues (the VBA code is paused at this point).

1

2

3 4

5 6

7

8 VBA code example of a Private procedure

MsgBox Function – prompting user with a Yes or No response

Page 23: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 14

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!).

4. If the value of the variable MyResponse was a 6 then this line will execute and show a MsgBox statement (The If test was True).

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.

6. If the value of the variable MyResponse was not a 6 then this line will execute and show a MsgBox statement (The If test was False).

7. This is the end of the If test block (End If). The next line of code (if any) would continue.

8. The procedure comes to an end.

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.

MsgBox Statement – if Yes was chosen

MsgBox Statement – if No was chosen

Page 24: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 15

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(...)

…[VBA code here]

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(...)

…[VBA code here]

End Sub

Public Sub subName(...)

…[VBA code here]

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.

Page 25: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 16

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.

Think of a function as a sub procedure with attitude; it answers you back!

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(...)

…[VBA code here]

functionName = …[the result]

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.

VBA Module – four procedures each with a hard break line

Page 26: Welcome to Microsoft Access VBA - Access Database Tutorial

A c c e s s D a t a b a s e T u t o r i a l – M i c r o s o f t A c c e s s V B A P r o g r a m m i n g

https://accessdatabasetutorial.com/ 17

There you have it.

I hope you found this reference guide very useful?

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.

Ben Beitler – “Your Access Database Expert”

Please visit our website:

AccessDatabaseTutorial.com

Thank You J