Mod Operator

You can find the remainder in Integer division by using the modulus operator (mod)
The Mod operator returns the remainder after division

8 Mod 3 = 2 

This is extremely useful when you have a loop and you want to perform an action every nth times through a loop.

For icounter = 1 To 100 
   If icounter Mod 10 Then
'every tenth value
   End If
Next icounter

This is similar to the integer division except it only returns the remainder

10 mod 3 = 1

This is actually equivalent to the following maths formula
a - (b * (a \ b))
a - (b * Fix(a / b))

You can also get overflow errors in VBA using the Mod operator with very large numbers. For example,

Public Sub Mod_Error() 
    Dim Number As Double
    Dim Divisor As Double
    Dim Result As Double
    Number = 2 ^ 31
    Divisor = 7
    Result = Number Mod Divisor ' Overflow error here.
End Sub

© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext