How do I use the MOD operator in VBA?

The MOD operator in VBA is used to divide two numbers and return the remainder of the division. This is useful for tasks such as verifying if a number is even or odd, or if a number is a multiple of another number. To use the MOD operator, simply use the syntax ‘x MOD y’, where x is the dividend and y is the divisor. The result of the operation will be the remainder of the division.


You can use the Mod operator in VBA to calculate the remainder of a division.

Here are two common ways to use this operator in practice.

Method 1: Use Mod Operator with Hard Coded Values

Sub UseMod()
Range("A1") = 20 Mod 6
End Sub

This particular example will return the remainder of 20 divided by 6 in cell A1.

Method 2: Use Mod Operator with Cell References

Sub UseMod()
Range("C2") = Range("A2") Mod Range("B2")
End Sub

This particular example will calculate the remainder of the value in cell A2 divided by the value in cell B2 and output the result in cell C2.

The following examples show how to use each method in practice.

Example 1: Use Mod Operator with Hard Coded Values

Suppose we would like to calculate the remainder of 20 divided by 6 and output the result in cell A1.

We can create the following macro to do so:

Sub UseMod()
Range("A1") = 20 Mod 6
End Sub

When we run this macro, we receive the following output:

The result of 20 Mod 6 turns is 2.

This value is shown in cell A1, just as we specified in the macro.

Example 2: Use Mod Operator with Cell References

Suppose we would like to calculate the remainder of the value in cell A2 divided by the value in cell B2 and output the result in cell C2.

We can create the following macro to do so:

Sub UseMod()
Range("C2") = Range("A2") Mod Range("B2")
End Sub

When we run this macro, we receive the following output:

The result of 20 Mod 6 turns is 2.

This value is shown in cell C2, just as we specified in the macro.

Note: You can find the complete documentation for the VBA Mod operator .

x