Skip to Content
Access™ 2007 VBA Programmer's Reference
book

Access™ 2007 VBA Programmer's Reference

by Teresa Hennig, Rob Cooper, Geoffrey Griffith, Armen Stein
May 2007
Intermediate to advanced
1152 pages
30h 53m
English
Wrox
Content preview from Access™ 2007 VBA Programmer's Reference

8.3. Evaluating Expressions in VBA

Expressions are one of the basic building blocks of any programming language. There are several ways to evaluate expressions in VBA so that you can control the flow of your procedural logic.

8.3.1. If .. Then

Nearly, every programming language has some way of asking If, and VBA is no exception. The If..Then structure is one of the most commonly used in VBA. Its usage is straightforward, but there are a couple of issues that warrant extra attention. First, the expression you are using needs to be formed correctly and completely. One common mistake is to use an expression like this:

If intOrderStatus = 1 Or 2 Then
  'some interesting code here
End If

The problem here is that a complete Boolean (true or false) expression needs to be on both sides of the Or. The literal way to interpret this expression is "if intOrderStatus = 1 or if 2 is True, then," which, of course, makes no sense. The value 2 is not true. In fact, in Access VBA any value other than −1 is false, so the value 2 is always false. This If statement has a big problem—the interesting code will run if the order status is 1, but it will never run if it is 2.

The correct way to write this line of code is as follows:

If intOrderStatus = 1 Or intOrderStatus = 2 Then
  'some interesting code here
End If

It's repetitive, but you have to tell VBA exactly what you want to do.

Instead of using multiple Or operators in SQL statements, you can use a much easier syntax: the In operator. In SQL, the ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Excel® 2007 VBA Programmer's Reference

Excel® 2007 VBA Programmer's Reference

John Green, Stephen Bullen, Rob Bovey, Michael Alexander
Access 2003 VBA Programmer's Reference

Access 2003 VBA Programmer's Reference

Patricia Cardoza, Teresa Hennig, Graham Seach, Armen Stein
Microsoft® Access® 2010 Programmer's Reference

Microsoft® Access® 2010 Programmer's Reference

Teresa Hennig, Rob Cooper, Geoffrey L. Griffith, Jerry Dennison

Publisher Resources

ISBN: 9780470047033Purchase book