The VBA function "Round"

Rank

New Member
Joined
Aug 29, 2005
Messages
28
Hi!

I discovered this lately and wanted to share it with other VBA programmers!
:warning:
First, I think that the best way to explain it is to demonstrate what I'm talking about, so, simply copy-paste the code below in a Excel Module and run it:

Code:
Sub test()
   Dim d As Double
   Dim i As Integer
   
   'VBA round function
   For i = 1 To 5
      d = i + 0.5
      MsgBox "VBA Round of " & d & " is " & Round(d, 0)
   Next i
   
End Sub

You will see that 1.5=2; 2.5=2; 3.5=4 and 4.5=4...
:huh: since when round of 2.5 is 2 ????

Ok, then, now, replace the "Round" by "Application.WorksheetFunction.Round":
Code:
   'Worksheet round function
   For i = 1 To 5
      d = i + 0.5
      MsgBox "Excel Round of " & d & " is " & Application.WorksheetFunction.Round(d, 0)
   Next i
Now, you see that 1.5=2 and 2.5=3...
that is correct!

I've also checked VB6 and there's the same problem...
:roll:

So, if you're using that function, be aware that it appears to be uncorrect...
 

Excel Facts

Copy a format multiple times
Select a formatted range. Double-click the Format Painter (left side of Home tab). You can paste formatting multiple times. Esc to stop
Thanks for the heads-up.

I think I read somewhere that ROUND in VBA rounds towards 0 (ie down for +ve, up for -ve) whereas in Excel it always rounds up. I'll see if I can track the reference down.

Denis
 
Upvote 0

Forum statistics

Threads
1,224,876
Messages
6,181,519
Members
453,050
Latest member
Obil

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top