
Tips.Net > WordTips Home > Macros > Creating Macros > Understanding Precedence
Summary: Macros often contain mathematical formulas, some of them quite complex. When a formula contains more than one operator (such as + or -), VBA needs to figure out in which order to perform the operations. Here's how it's done. (This tip works with Microsoft Word 6, Word 95, Word 97, Word 2000, Word 2002, and Word 2003.)
Macros often contain mathematical formulas. Those formulas can sometimes become quite complex. Any time a formula contains more than one operator (such as + or -), VBA needs to figure out in which order to perform the operations. This is where the concept of precedence comes into play. Precedence is the built-in macro logic that determines the order in which the operations occur. This is the normal order:
| Operator | Meaning | |
|---|---|---|
| ^ | Exponentiation | |
| - | Negation | |
| * and / | Multiplication and division | |
| \ | Integer division | |
| Mod | Modulus | |
| + and - | Addition and subtraction |
Notice that there are two entries in the precedence list in which there are two operators. Multiplication and division are at the same precedence level, as are addition and subtraction. If a formula involves two or more operators at the same precedence level, then the operators are evaluated from left to right within the formula.
If you want to change the order in which a formula is evaluated, you need to use parentheses. Operations within parentheses are evaluated before those outside of them. Thus, a formula such as 3 * (4 + 2) would produce a result of 18 because the addition within the parentheses takes precedence over the multiplication outside the parentheses. If the parentheses had been omitted, then 3 * 4 + 2 would have resulted in 14.
Tip #1452 applies to Microsoft Word versions: 6 95 97 2000 2002 2003
Ultimate Library! An amazing resource that brings together, in one place, the collected knowledge of everything ever published in WordTips. The library combines two powerful elements to make you more productive: solutions and convenience. Here's where you get your own copy of everything ever published in WordTips.
Check out WordTips Ten-Year Library today!
Discover how to use Word's mail merge tool to create your own custom documents in just minutes. Great e-book answers all your questions. (more information...)
Ask a Word Question
Make a Comment
Bugs and Pests Tips
ExcelTips
Family Tips
Health Tips
Home Tips
Organizing Tips
WordTips