Introduction | Example | Tutorial | Applications | Comments
Introduction - VBA Backslash
Using a backslash (\) instead of a forward slash (/) to divide two numbers in VBA will divide the numbers but will round the quotient and return an integer solution.
Well, that’s not entirely true… The backslash operator will always return an integer, but it doesn’t round the quotient. It actually rounds the two numbers you’re dividing first and then truncates the quotient. It rounds the two numbers you’re dividing using Banker’s Rounding. In this manner, it behaves much like the VBA Mod operator.
Let’s drive that point home with an example.
Example - VBA Backslash
VBA Integer Division
Sub IntegerDivide() Debug.Print 10.5 \ 4.5 'Integer Division = 2 Debug.Print 10.5 / 4.5 'Regular Division = 2.33 Debug.Print 10.5 \ 3.5 'Integer Division = 2 Debug.Print 10.5 / 3.5 'Regular Division = 3 End Sub
Becoming a VBA expert isn't hard
Over 5000 members are improving their VBA skills for free with our email tutorials. Why don't you join them? Our experts share time-saving VBA tips and we'll give you access to our huge macro library - it's sure to speed up your macro development.
Tutorial - VBA Backslash
Explaining how Integer Division works in VBA
This example proves that the backslash operator doesn’t just round the final answer. When you normally divide 10.5 by 3.5, you get a 3. You would expect the integer division method to produce a quotient of 3, as well, right?
That’s not what happens. Since the \ operator divides the two numbers first, and it does so with Banker’s Rounding where each number is rounded to the nearest even number, you’re actually dividing the number 10 by the number 4.
10 divided by 4 is 2.5, which you would also think would round to 3, but again that’s not what happens! Integer division doesn’t ever round your final answer. It truncates it.
Let’s look at another example where we divide 11 by 4 using regular division, and again using the backslash (\) integer division.
Sub IntegerDivide2() Debug.Print 11 / 4 'Regular Division = 2.75 Debug.Print 11 \ 4 'Integer Division = 2 End Sub
The quotient 2.75 will surely round up when using integer division, right? Nope! It’s truncated to 2.
I can’t tell you how many times I’ve forced the quotient of my division to an integer using the VBA Round Function or the VBA CInt Function. All this time I could have just used a backslash when I divided and it’d automatically happen for me!
Of course, you’ve still gotta be careful and recognize how integer division works to make sure it produces the desired results in your spreadsheet.
If you liked this VBA tutorial, I hope you’ll shop my VBA Store to show your support for wellsr.com. Here, you’ll find helpful cheat sheets and Excel products to help you master VBA. Without revenue from great readers like you, it’s difficult to grow the site and reach more users.