Introduction | Example | Tutorial | Applications
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
Make powerful spreadsheets with our free VBA Developer's Guide Tutorials like this can be complicated. That’s why we created our free VBA Developer Guide to supplement this tutorial. Grab it now and we’ll also send you a bunch of pre-built macros.
Tutorials like this can be complicated. That’s why we created our free VBA Developer Guide to supplement this tutorial. Grab it now and we’ll also send you a bunch of pre-built macros.
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.
This was a unique tutorial, but we’re just getting started. When you’re ready to take your VBA to the next level, subscribe using the form below.