Is there a vba equivalent to excel\'s mod
function?
Function Remainder(Dividend As Variant, Divisor As Variant) As Variant
Remainder = Dividend - Divisor * Int(Dividend / Divisor)
End Function
This function always works and is the exact copy of the Excel function.
Be very careful with the Excel MOD(a,b) function and the VBA a Mod b operator. Excel returns a floating point result and VBA an integer.
In Excel =Mod(90.123,90) returns 0.123000000000005 instead of 0.123 In VBA 90.123 Mod 90 returns 0
They are certainly not equivalent!
Equivalent are: In Excel: =Round(Mod(90.123,90),3) returning 0.123 and In VBA: ((90.123 * 1000) Mod 90000)/1000 returning also 0.123
The Mod operator, is roughly equivalent to the MOD function:
number Mod divisor
is roughly equivalent to MOD(number, divisor)
.
You want the mod operator.
The expression a Mod b is equivalent to the following formula:
a - (b * (a \ b))
Edited to add:
There are some special cases you may have to consider, because Excel is using floating point math (and returns a float
), which the VBA function returns an integer. Because of this, using mod
with floating-point numbers may require extra attention:
Excel's results may not correspond exactly with what you would predict; this is covered briefly here (see topmost answer) and at great length here.
As @André points out in the comments, negative numbers may round in the opposite direction from what you expect. The Fix()
function he suggests is explained here (MSDN).
In vba the function is MOD. e.g
5 MOD 2
Here is a useful link.
The top answer is actually wrong.
The suggested equation:
a - (b * (a \ b))
Will solve to: a - a
Which is of course 0 in all cases.
The correct equation is:
a - (b * INT(a \ b))
Or, if the number (a) can be negative, use this:
a - (b * FIX(a \ b))