2007 Even/Odd/MOD

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
 
M

Mike H

Hi,

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

q = WorksheetFunction.IsEven(MyNumber)

Mike
 
R

Rick Rothstein

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

Rick Rothstein

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Remove All VBA 8
Lost VBA 3
User Created Menu 3
DateSerial vs Date?? 2
xlsm SaveAs xls 4
conditional formatting w/ check for beginning odd or even 4
Eliminate Taskbar updates 2
Odd or Even Test 9

Top