Monday, 29. September 2008
Problem in VB MOd operator for Double data type

Recently while i was learning to use VB for Microsoft Excel, i was stuck in an strange problem while using the Mod operator. The operation thew Overflow Error whenever i tried to perform the Mod operation on a double. After googling the problem, i found it was a common problem and it took me no time to get to the solution.

I got the error when on following statement:
49773387027# Mod 221

The Mod is an integer operation, whereas Double is a floating point number. The Mod operation will throw "Overflow Error" if either operand is larger than 231 - 1.

So i created my own function as shown below:
Private Function findMod(number As Double, divisor As Double) As Double

    Dim temp1 As Double
    Dim temp2 As Double
    Dim result As Double
    temp1 = Fix(number / divisor)
    temp2 = temp1 * divisor
    result = number - temp2
    findMod = result

End Function
This worked perfectly for me.

... comment