9.22.2008

VBA - Integer Division and Mod

Many Microsoft Project users are not professional programmers so they might not be aware of some of the basics of visual basic. One of them which surprised me when I first ran across it was the "integer division" operator. Now most people know the typical add + , subtract -, multiply *, and divide / operators and what results they bring. But there are really two more which are quite useful in certain situations.

The first is the integer division operator which is a backslash "\". Do not confuse this with the forward slash "/" which is used for regular division. The results of this operator are that division takes place as usual except any non-integer remainder is discarded. Here are a couple of examples to illustrate.

10/4 = 2.5
10\4 = 2

5.423/1 = 5.423
5.423\1 = 5

As you can probably guess, integer division is a handy way of dividing and rounding down in a single step.

Another related operator is the MOD operator. It is similar to integer division only it returns only the remainder. Here are a couple of examples.

6 MOD 4 = 2
12 MOD 4 = 0

By putting them together you can break numbers into their component parts. Doing date math is an easy way to see how this works. Let's let "Days" be a number of days. We want to know how many weeks and how many days it is. The following formula would return how many weeks and how many days there are in that amount of time.

Days\7 & " Weeks, " & Days MOD 7 & " Days"

If Days is 23 days, then the result would be:

3 Weeks, 2 Days

last-Samu1241's Blog © 2008. Template by Dicas Blogger.

TOPO