VBA operators: calculating and joining text
Macros calculate all the time: quantity times price, totals, percentages, boxes and leftovers. You know most operators from Excel formulas. VBA adds two that formulas do not have in this form, plus &, which joins numbers and text into a sentence.
In short: + - * / as in Excel, ^ for powers, \ divides and drops the decimals, Mod gives the remainder. & joins text: "Total: " & total. Multiplication before addition, parentheses first.
What you need to know: Variables and MsgBox.
Try it right now
One order line: quantity times price gives the amount. The macro writes the finished number into the cell, not a formula.
Task Work out the order amount: quantity (B2) times price (C2). Put the result in D2 as a number, not a formula.
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Item | Qty | Price | Amount |
| 2 | Ergonomic office chair | 6 | 189.90 | |
| 3 | ||||
| 4 | ||||
| 5 |
The operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 250 + 12 | 262 |
- | subtract | 250 - 12 | 238 |
* | multiply | 6 * 189.9 | 1139.4 |
/ | divide | 250 / 12 | 20.8333… |
\ | integer division, decimals dropped | 250 \ 12 | 20 |
Mod | remainder of integer division | 250 Mod 12 | 10 |
^ | to the power of | 1.02 ^ 3 | 1.061208 |
& | join text | "No. " & 1043 | No. 1043 |
Decimals in code always use a point: 0.2. VBA code is the same whatever language Excel runs in, so a colleague with a German or French Excel can run your macro unchanged. The comma separates arguments.
VBA works in this order: parentheses first, then ^, then * and /, then \, then Mod, then + and -, and & last. Operators of equal rank go from left to right. When in doubt, add parentheses; they never hurt.
One more exercise: boxes and leftovers
250 units, 12 fit in a box. How many full boxes are there, and how many units are left over? That is exactly what \ and Mod are for.
Task How many full boxes are there, and how many units are left over? Write the number of full boxes to B5 and the remainder to B6. Use \ (integer division) and Mod (remainder).
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Shipping | |||
| 2 | Units | 250 | ||
| 3 | Units per box | 12 | ||
| 4 | ||||
| 5 | Full boxes | |||
| 6 | Units left |
Mod comes in handy elsewhere too: n Mod 2 = 0 means "even number", and minutes Mod 60 gives the minutes past the full hour.
Joining text with &
Dim hours As Double
hours = (Range("B2").Value - Range("B3").Value) / 60
Range("B5").Value = "Hours worked: " & hours
& turns everything into text and joins it. It adds no spaces of its own; those go inside the quotes. When a decimal number becomes text, VBA takes the decimal separator from the computer's regional settings: "7.5" in the US or UK, "7,5" on a German PC. For a fixed number of decimals, such as "7.50", you need the Format function, which comes up in level 3.
Why not + for text? + does join two pieces of text, but as soon as a number is involved, VBA wants to add. "Hours worked: " + 8 stops with "Run-time error '13': Type mismatch". With & that cannot happen.
Task Write the text "Hours worked: 8" to B5: time on site minus break, divided by 60, with the text in front. Check produces decimals, such as "Hours worked: 7.5".
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Working time | |||
| 2 | On site (minutes) | 510 | ||
| 3 | Break (minutes) | 30 | ||
| 4 | ||||
| 5 | Result |
In real Excel
For a quick calculation, use the Immediate window in the VBA editor (Ctrl+G): a question mark in front shows the result, as in ?250 \ 12 or ?"No. " & 1043. A macro that writes results into cells as numbers calculates once and then stops. If the inputs change, run it again. If the sheet should keep calculating on its own, have the macro write a formula instead, as in the recording lesson.
Common mistakes
Forgetting the parentheses
Range("B2").Value - Range("B3").Value / 60 divides only the break by 60, and B5 ends up as "Hours worked: 509.5" instead of "Hours worked: 8". Subtract first, then divide: the difference belongs in parentheses.
/ instead of \
With / you get 20.83 boxes, and Check reports 20.83333333 in B5 where 20 is expected. For "how many times does it fit completely", use \.
Dividing by zero
An empty cell counts as 0. Divide by it and VBA reports "Run-time error '11': Division by zero". Check with If first whether the divisor is 0.
A comma inside a number
If you are used to European number formats, amount * 0,2 slips in easily. VBA reads the comma as a separator and reports "Compile error: Expected: end of statement". In code, decimals always take a point.
FAQ
How do I round to two decimals?
With Round(amount, 2). Note that VBA rounds an exact half to the nearest even digit (2.5 becomes 2, 3.5 becomes 4), while Excel's ROUND function rounds halves away from zero. For invoices people often use WorksheetFunction.Round, which comes up in level 3.
Why does the cell show 1139.4 instead of 1,139.40?
The macro only writes the number. How it looks depends on the cell's number format. Range("D2").NumberFormat = "#,##0.00" sets two decimals and a thousands separator.
Does VBA calculate exactly like Excel?
Almost. Both store decimals with about 15 digits of precision, so a result like 0.1 + 0.2 can be a tiny bit off 0.3. Round before you compare decimals.