VBA equivalent to Excel's mod function

后端 未结 8 1167
抹茶落季
抹茶落季 2020-11-27 06:31

Is there a vba equivalent to excel\'s mod function?

相关标签:
8条回答
  • 2020-11-27 06:57
    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.

    0 讨论(0)
  • 2020-11-27 07:03

    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

    0 讨论(0)
  • 2020-11-27 07:03

    The Mod operator, is roughly equivalent to the MOD function:

    number Mod divisor is roughly equivalent to MOD(number, divisor).

    0 讨论(0)
  • 2020-11-27 07:05

    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).

    0 讨论(0)
  • 2020-11-27 07:09

    In vba the function is MOD. e.g

     5 MOD 2
    

    Here is a useful link.

    0 讨论(0)
  • 2020-11-27 07:13

    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))

    0 讨论(0)
提交回复
热议问题