473,387 Members | 1,512 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,387 developers and data experts.

Avoid IIf(), Switch(), and Choose() in VBA code

ADezii
8,834 Expert 8TB
The tendency of VBA code to evaluate all expressions, whether or not they need to be evaluated from a logical standpoint, makes the use of the IIf(), Switch(), and Choose() Functions inefficient and downright dangerous. For these reasons, they should 'never' be used in VBA code. A couple of examples using IIf() will clearly illustrate this point which applies equally well to Choose() and Switch().

Example 1:
Expand|Select|Wrap|Line Numbers
  1. varValue = IIf(BooleanExpression, Function1(), Function2())
Both Functions will be called possibly leading to undesireable side effects, and a definate slowdown of you program execution. The If...Then...Else construct, although longer, would be more efficient since only 1 Function will be called. Again, the same applies to both Choose() and Switch(). Here is the more efficient method:
Expand|Select|Wrap|Line Numbers
  1. 'only 1 Function is called depending on the outcome of BooleanExpression
  2. If BooleanExpression Then
  3.    varValue = Function1()
  4. Else
  5.    varValue = Function2()
  6. End If
Example 2:
Expand|Select|Wrap|Line Numbers
  1. dblNew = IIf(intY = 0, 0, intX / intY)
The above line of code would at first appear relatively harmless since it apparently covers the case where intY = 0, but this is far from True. Remember, the 2nd expression will also be evaluated and it will subsequently generate a runtime Error (Division by 0).

NOTE: I saved the best for last! These Functions when used in Queries, Forms, or Reports do not exhibit the same behavior and work exactly as you would expect. It is only in VBA code, in a Module, where you need to avoid IIf(), Switch(), and Choose().
Mar 3 '07 #1
14 24982
NeoPa
32,556 Expert Mod 16PB
This is an important point to make ADezii.
However, I think to avoid these quite useful functions altogether simply because they can, in certain limited circumstances, noticeably degrade the performance of a project, is possibly overkill.
These limitations are certainly worth bearing in mind, especially if the various options execute large amounts of, or particularly slow, code.

On your last point, this is very interesting and I'd be very interested in a link to allow me to investigate further. I was unaware of any such difference in the SQL versions of these functions.
Mar 4 '07 #2
ADezii
8,834 Expert 8TB
This is an important point to make ADezii.
However, I think to avoid these quite useful functions altogether simply because they can, in certain limited circumstances, noticeably degrade the performance of a project, is possibly overkill.
These limitations are certainly worth bearing in mind, especially if the various options execute large amounts of, or particularly slow, code.

On your last point, this is very interesting and I'd be very interested in a link to allow me to investigate further. I was unaware of any such difference in the SQL versions of these functions.
I must confess that I was a little hesitant about this particular Tip since I know that you are quite fond of these 3 Functions. Please don't take it personally, I just find the details relating to them very interesting.

NOTE: The reference source for this particular Tip is The Access 2002 Desktop Developer's Handbook by Paul Litwin, Ken Getz, and Mike Gunderloy. The specific location is Chapter 15 - Application Optimization, Test 17: Watch Out for IIf - It Doesn't Short-Circuit.
Mar 4 '07 #3
NeoPa
32,556 Expert Mod 16PB
Personally, I think you were right to make the point my friend.
The emphasis may have been over-strong, but considering the target audience, it's an important point that people should, at least, be aware of.
There are certainly situations where I wouldn't dream of using them (Actually, though I was aware of the IIf() problem I didn't realise it covered Choose() & Switch() too).
People with very large databases who are looking to use the Domain Aggregate functions within one of these functions should be particularly cautious. I only use them with either very small datasets or when it is impossible to get the same functionality using a sub-query in SQL (which is very rare).

It's a shame you found it in a book as I wanted to read through it myself (easily - you know, on the web).
Mar 5 '07 #4
Rabbit
12,516 Expert Mod 8TB
Tip #3 should be: How to use the help files.
Mar 7 '07 #5
NeoPa
32,556 Expert Mod 16PB
Yeah, but they change so drastically for each version that would be a tome in itself :D
Mar 7 '07 #6
Rabbit
12,516 Expert Mod 8TB
Yeah but some things are common like if you highlight a function and press F1 it will bring up the help file for it. Or if you don't know what a property does you can focus on the property and press F1 to bring up that help file. And how these things bring up different help files depending on if you're in Access or the Visual Basic Editor. And how they should look look at the See Also list for related topics.
Mar 8 '07 #7
NeoPa
32,556 Expert Mod 16PB
Very fair point.
I was hoping to find time to do one on debugging at some stage. Please feel free to take this one on if you feel inclined. I agree that it may well be very helpful and save many explanations - if we could say RTFM (Or the help file equivalent) while pointing them at such a helpful (excuse the pun) Tutorial.
Mar 9 '07 #8
Denburt
1,356 Expert 1GB
NEO I thought I read about this in the helpfile so I was in my VBA just now an typed in IIF, Switch, and Choose highlighted it hit F1 and each one was in there the point ADezii is making is right near the bottom. :)
Mar 22 '07 #9
Denburt
1,356 Expert 1GB
OK I looked it up just for fun it is on the web on the Microsoft Site.

Developer Handbook Chapter 15
Mar 22 '07 #10
NeoPa
32,556 Expert Mod 16PB
NEO I thought I read about this in the helpfile so I was in my VBA just now an typed in IIF, Switch, and Choose highlighted it hit F1 and each one was in there the point ADezii is making is right near the bottom. :)
Cheers Denburt.
I checked out the helpfile as you said, and the bit about evaluating both sides is there. What isn't, is the bit about it not being the same in the SQL engine. In other words, if you use it in a query, you will not suffer from the same drawback.
I've been aware of the full evaluation bit for a while, but the SQL bit was new to me and, I admit, a bit of a surprise. It's good that we can learn so much new stuff here :)
Mar 22 '07 #11
NeoPa
32,556 Expert Mod 16PB
OK I looked it up just for fun it is on the web on the Microsoft Site.

Developer Handbook Chapter 15
Checking your new link out now...
Mar 22 '07 #12
Denburt
1,356 Expert 1GB
It's good that we can learn so much new stuff here
So true I am still learning every day and I have been doing this for so long I have forgotten more than a lot of Access users will probably ever know so it is good to see refreshing bits like this.
Mar 22 '07 #13
NeoPa
32,556 Expert Mod 16PB
I found what I was looking for in your link.
It was the Note under Test 17.
Note: The IIf function used in queries, forms, or reports doesn't have this same behavior—that is, it works as you'd expect it to in those places. It's only in VBA code, in a module, where you need to avoid IIf because of its overzealous evaluation tendencies.
Unfortunately, I actually expect it to evaluate the expressions fully before running :s
Mar 22 '07 #14
Denburt
1,356 Expert 1GB
O.K. Found this, It can dog your queries down too if it is in a nested query.
At the bottom of this link although the whole page is worth reading (or reviewing):
Microsoft Jet Database Engine Programmer's Guide - Chapter 4

Common Pitfalls

Many common mistakes can cause unnecessary bottlenecks when you are running queries. Following is a list of these common mistakes and what to do to correct them.


Including expressions in query output. Placing expressions, such as an IIf on an output field of a query can cause optimization problems if the query is used as the input to another query. For example, consider the following two queries, where the first query is saved as Q1:

SELECT IIf(ShipVia = 2, 'United Package', 'Other') AS ShipperName FROM Orders; SELECT * FROM Q1 WHERE ShipperName = 'United Package';

Because Microsoft Jet can't optimize the IIf expression in the first query, it can't optimize the second query. Expressions can get buried so far down in a query tree that it's easy to forget about them. If expressions are necessary in the output, try to place the expression in a control on a form or report.

The following query replaces the previous two queries and is the optimal way to write this query:

SELECT * FROM Orders WHERE ShipVia = 2;



Using GROUP BY on too many fields. When you're creating a totals query, use the GROUP BY clause on as few fields as necessary to achieve the query's goal. The more fields in the GROUP BY clause, the longer the query takes to execute. Make sure you don't include extraneous fields.


Using GROUP BY in same query as a join. If possible, place a GROUP BY clause on a table and then join it to another table, rather than joining the two tables and using the GROUP BY clause in the same query as the join. For example, instead of this query

SELECT Orders.CustomerID, Count(Orders.OrderID) AS CountOfOrderID FROM Customers INNER JOIN Orders ON Customers.CustomerID = Orders.CustomerID GROUP BY Orders.CustomerID;

you may benefit by using two separate queries, as follows, where the first query is saved as SelectWithGroupByQ1:

SELECT Customers.CustomerID FROM Customers GROUP BY Customers.CustomerID; SELECT Orders.CustomerID, Count(Orders.OrderID) AS CountOfOrderID FROM SelectWithGroupByQ1, INNER JOIN Orders ON Q1.CustomerID = Orders.CustomerID GROUP BY Orders.CustomerID;



Not including indexes on join fields. When you're joining tables, always try to index the fields on both sides of a join. This can speed up query execution by allowing more sophisticated join strategies such as index and index-merge joins. The use of indexes also provides better statistics. For more information, see the "Join Strategies" section earlier in this chapter.


Under-indexing fields. In appropriate circumstances, for example where the database is used solely for decision-support types of applications, you can place an index on all fields that have unique values and are used in a join or as a restriction. By using Rushmore query optimization, Microsoft Jet can take advantage of multiple indexes on a single table. This makes indexing many fields advantageous. However, keep in mind that adding indexes to fields can cause performance to suffer.


Using Count(fieldname) instead of Count(*). When you have to determine the number of records, you should use Count(*) rather than Count(fieldname) because there are Rushmore optimizations that allow Count(*) to be executed much more quickly than Count(fieldname).
Mar 22 '07 #15

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: jabailo | last post by:
For web services, is there a way to have VS.NET '03 automatically 'switch to code view' when clicking on a asmx file in the solution.
2
by: John Black | last post by:
Hi, I wonder if there is any good way in debugging the code not steping into STL code, it is easy to do in normal statement, just click "step over", but when there are some STL type variable on...
14
by: Howard Kaikow | last post by:
Can I use a bookmark to selectively choose the code to be run? For example. Suppose we have the following in an HTML file: <html>
13
by: Fei Liu | last post by:
Hi Group, I've got a problem I couldn't find a good solution. I am working with scientific data files in netCDF format. One of the properties of netCDF data is that the actual type of data is only...
12
by: Steve | last post by:
Can the Choose function be used to set the criteria for a field in a query to either "Is Null" or "Is Not Null" based on the value of an option Group on a form? Such as:...
4
by: jhoiland | last post by:
Hello, I am writing some pricing optimizations for an online store. What I am trying to do is adjust the sale price based upon a combination of 3 factors...cost, weight, min advertised price...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.