Is there a vba equivalent to excel's mod
function?
This question is related to
excel
excel-2007
vba
My way to replicate Excel's MOD(a,b)
in VBA is to use XLMod(a,b)
in VBA where you include the function:
Function XLMod(a, b)
' This replicates the Excel MOD function
XLMod = a - b * Int(a / b)
End Function
in your VBA Module
But if you just want to tell the difference between an odd iteration and an even iteration, this works just fine:
If i Mod 2 > 0 then 'this is an odd
'Do Something
Else 'it is even
'Do Something Else
End If
The Mod
operator, is roughly equivalent to the MOD
function:
number Mod divisor
is roughly equivalent to MOD(number, divisor)
.
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 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))
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.
Source: Stackoverflow.com