Table des matières
Mod Operator
Le Mod operator dans Excel VBA gives the remainder of a division. This page starts with some simple examples.
Mod 101
Place a command button on your worksheet and add the following code line:
MsgBox 7 Mod 2
Résultat lorsque vous cliquez sur le bouton de commande sur la feuille:
Explication: 7 divisé par 2 est égal à 3 avec un reste de 1.
Ligne de code:
MsgBox 8 Mod 2
Résultat:
Explanation: 8 divided by 2 equals 4 with a remainder of 0.
Even or Odd
Let’s create a program that uses the Mod operator to check if a number is even or odd.
Code lines:
Dim x As Integer
x = Range(“A1”).Value
If x Mod 2 = 0 Then
Range(“B1”).Value = “Even”
Autre
Range(“B1”).Value = “Odd”
Fin si
For example enter the value 100 into cell A1 and click the command button on the sheet.
Résultat:
Explanation: a number is even if it is divisible by 2 without a remainder.
Divisible by Another Number
Let’s create a program that uses the Mod operator to check if a number is divisible by another number.
Code lines:
Dim x As Integer
x = Range(“A1”).Value
If x Mod 4 = 0 Then
Range(“B1”).Value = “Divisible by 4”
Autre
Range(“B1”).Value = “Not divisible by 4”
Fin si
For example enter the value 50 into cell A1 and click the command button on the sheet.
Résultat:
Explanation: 50 divided by 4 equals 12 with a remainder of 2. In other words 50 is not divisible by 4.