If Statements

The If statement is probably one of the most widely used statements. It checks a Boolean value or the value of a Boolean comparison and if it is TRUE, code runs. You can have a single line If statement or a code block ended by End If. One thing I notice is that some people have a Boolean value but they still put a test in to see whether it is TRUE, which is unnecessary. For example, the IsNumeric statement returns a Boolean. Putting in IsNumeric(x) = TRUE is the same as putting in IsNumeric(x). Putting in IsNumeric(x) = False is the same as putting in Not IsNumeric(x). See the following example.

Dim x As String
Dim y As Double
x = InputBox("Enter a number", "Input Required")
If IsNumeric(x) Then
   y = CDbl(x)
   If y / 2 = Int(y / 2) Then MsgBox "Number is Even", vbInformation
   If y / 2 <> Int(y / 2) Then MsgBox "Number is Odd", vbInformation
End If
If Not IsNumeric(x) Then MsgBox "You did not enter a number", vbInformation

If you are in Excel, you can use the worksheet functions IsEven and IsOdd. However, testing whether a number divided by two is equal to the integer of that result is another way to test whether a number is even.

Get Integrating Excel and Access now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.