Saturday, July 20, 2019 Useful Resources for Industrial Technology Enthusiasts!

  Automation & Control - Technical Bits
  If-Then-Else Statements

We can use the If-Then-Else statement to run a specific statement or a block of statements, depending on the value of a condition.  If-Then-Else statements can be nested to as many levels as you need.

TIP: However, for readability, you should use Select Case statement rather than multiple levels of nested If...Then...Else statements.

Examples: IF-THEN-ELSE Statements


IF-THEN-ELSE Statements : if a Condition is True


Use it when only one condition is True, you can use the single-line syntax of the IF-THEN-ELSE statement.

This following example shows the single-line syntax, omitting the Else:

Sub myDate()
    myDate = #1/1/99#
    If myDate < Now Then myDate = Now
End Sub
 To run more than one line of code, you must use the multiple-line syntax. 
This syntax includes the End If statement, as shown in the following example:
Sub AlertUser(value as Long)
   IF value = 0 THEN
        Msgbox “Hello Automation Guru”
        ValveOutput = 43
        Pump3 = True
    END IF
End Sub


IF-THEN-ELSE Statements : if a Condition is True and Running Others if It's False


You can use an IF-THEN-ELSE statement to define two blocks of executable statements:

one block runs if the condition is True,

the 2nd block runs if the condition is False.


Sub AlertUser(value as Long)
    If value = 1 Then
        Valve1Output = 43
        Pump3 = True
        SystemDown = 1
        SetAlarm21 = True
    End If
End Sub


IF-THEN-ELSE Statements : Use a Second Condition if the First Condition is False


You can add ElseIf statements to an IF-THEN-ELSE statement to test a second condition if the first condition is False.

For example, the following function procedure computes a damper output based on off set.

The statement following the Else statement runs if the conditions in all of the If and ElseIf statements are False.

Function UpdateValve(RealValue, offSet)
   If performance = 1 Then
        RealValue = offSet * 0.1
    ElseIf performance = 2 Then
        RealValue = offSet * 0.09
    ElseIf performance = 3 Then
        RealValue = offSet * 0.07
        RealValue = 0
    End If
End Function

Back Main Next


Site customized for Screen Resolution - 1400 x 1050
Site Map    I    Copyright © 2019 Automation Media. All rights reserved.