Microsoft Access VBA Macro Programming

(Tina Sui) #1
now,” and then rerun the procedure, and up comes another one! This can be very frustrating,
but the best answer to fixing it is to obey the rules of coding in the first place.
The following types of errors appear when the code is compiled, and are often referred to
as design-time or compile-time errors.

Runtime Errors


Runtime errors occur when your program is running. You could, for example, try to open a
file that does not exist, or attempt a division by zero. Such actions would create an error
message and halt execution of the program. They would not show up at compile time because
they are not breaking any programming rules, but they will prevent the code from running.

Logic Errors


Logic errors occur when your application does not perform the way you intended. The code
can be valid and run without producing any errors, but what happens is incorrect. These are
by far the most difficult errors to locate. They can require a lot of painstaking searching to
find, even using all the debugging tools at your disposal. It is very easy to keep looking at a
few lines of code and thinking, “There is nothing wrong with this. It should give the right
answer.” It is only by looking at each line in turn that you will see what has gone wrong, and
often suddenly realize what a simple mistake it was. You may also run into a situation you
did not envisage when first designing your code.

Design Time, Runtime, and Break Mode


When working on an application in VBA, you can be in three modes:

 Design time When you are working on the code for the application or designing a
form.
 Runtime When you run your code or your form. The title bar of the VBA screen will
contain the word “running,” and at this point you can view code but you cannot change it.
 Break If you pressCTRL+BREAK(pressing theCTRLkey at the bottom left of the
keyboard andPAUSE BREAKat the top right of the keyboard simultaneously) during
runtime, it will stop execution of your code. You can also insert a breakpoint by
pressing theF9 Key. Pressing it again removes it. You can insert a breakpoint from the
VBE menu by selecting Debug | Toggle Breakpoint. A dialog box will appear with the
error message, “Code execution has been interrupted,” displaying several buttons.
Clicking the Debug button will take you into the code window.

When you click Debug, you go into instant watch mode, also known as debug mode.
You’ll be able to see your code, and the line it has stopped at will be highlighted in yellow.
This is the line that is causing the problem. You can place your cursor on any variable that is

82 Microsoft Access 2010 VBA Macro Programming

Free download pdf