Home » excel » Excel VBA method ROUND is incorrect

Excel VBA method ROUND is incorrect

Posted by: admin April 23, 2020 Leave a comment

Questions:
Public Function foo()
Dim x As Double, y As Double, z As Double

x = 1.26
y = 3.175
z = Round(x + y, 2)

foo = z
End Function

Running Excel 2007 on Windows 7. This function returns 4.43 into a cell with =foo() which is annoying as I want 4.44. I found some documentation claiming VBA ROUND uses even rounding but here the last digit is odd. What is wrong here?

How to&Answers:

You can always use the Worksheet Round Function instead of VBA’s built-in one

Public Function foo2()
    Dim x As Double, y As Double, z As Double

    x = 1.26
    y = 3.175
    z = Application.WorksheetFunction.Round(x + y, 2)

    foo2 = z
End Function

foo2 will result in 4.44 (tested on my machine). I don’t know if this would affect performance at all.

Answer:

You will need to use decimal types to accomplish this which uses integer based arithmetic as opposed to floating point based.

Excel doesn’t have a native data type for this, so you have to use a Variant and then convert to a decimal using the CDec function.

Public Function foo()
    Dim x As Variant, y As Variant, z As Variant

    x = CDec(1.26)
    y = CDec(3.175)
    z = Round(x + y, 2)

    foo = z
End Function