2007 Even/Odd/MOD

  • Thread starter Thread starter Otto Moehrbach
  • Start date Start date
O

Otto Moehrbach

Excel 2007, Win 7 64-bit
In the past, I've always used 'MOD of X/2 =0' to determine if X is odd or
even. Has Microsoft come up with a shorter VBA function/command to do this
in 2007? Thanks for your time. Otto
 
Hi,

Nothing new I'm aware of but you can do this

q = WorksheetFunction.IsEven(MyNumber)

Mike
 
This is not new to XL2007; but, when using VB code, you can And your number
with 1 to see if it is odd or even. I believe doing it this way is even
quicker than using the Mod method (although that would only be significant
in a large loop). Consider this code...

If YourNumber And 1 Then
MsgBox "Your number is Odd"
Else
MsgBox "Your number is Even
End If

The logical expression "YourNumber And 1" returns either 1 if the number is
odd or 0 if the number is even, so you can test explicitly for those values
if you need or want to, but in an If..Then statement, 1 evaluates to True
and 0 evaluates to False, so normally you do not need to make that explicit
test (notice I left off the =1 from my test in my example code).
 
...in an If..Then statement, 1 evaluates to True and 0 evaluates to False

Just to clarify the above statement, the "general rule" is that in an
If..Then statement, 0 evaluates to False and **any** non-zero number equates
to True. The only two values "YourNumber And 1" can produce are 0 and 1,
hence my original statement.
 
Back
Top