VB2022 VB2019 VB6 VB Sample Code About Us

Lesson 7 If statement and IIf() Function


In our earlier lessons, we mastered the essentials of formulating Visual Basic code proficient in gathering user input and presenting output without managing the program's flow. Now, in this lesson, we're set to explore the realm of decision-making in VB code—a domain where we harness the power to interpret user input and steer the program's trajectory accordingly. The knack for decision-making stands as a pivotal facet of programming, empowering adept problem-solving and yielding purposeful output or feedback for users. Consider, for instance, the prospect of devising a program that guides the computer to perform designated tasks until a predefined condition receives fulfillment.

7.1 Conditional Operators

To manage the flow of a VB program, we leverage diverse conditional operators that bear a resemblance to mathematical counterparts. These robust tools empower the VB program to scrutinize data values, enabling it to make decisions on actions—be it program execution, termination, or other outcomes. Refer to Table 7.1 for a comprehensive display of these operators.

Table 7.1: Conditional Operators

Operator
Meaning
= Equal to
> More than
< Less Than
> More than or equal
<= Less than or equal
<> Not Equal to

7.2 Logical Operators

In addition to conditional operators, there are a few logical operators that offer added power to the VB programs. They are shown in Table 7.2.

Table 7.2:Logical Operators

Operator Description
And Both sides must be true
Or One side or other must be true
Xor One side or other must be true but not both
Not Negates true

* You can also compare strings with the operators. However, there are certain rules to be adhered to, where upper case letters are less than lowercase letters, and number are less than letters.

7.3 Using If...Then...Else Statements with Operators

To effectively control the VB program flow, we shall use If...Then...Else statement in conjunction with the conditional operators and logical operators.

If conditions Then

 VB expressions 

Else

 VB expressions 

End If

Example 7.1:

This program simulates a sign in process. If the username and password are correct, sign in is successful else sign in failed. Start VB6 and insert two textboxes onto the form, rename them UsrTxt and pwTxt, the first textbox is to accept username input and the second one for password input. For pwTxt, set the PasswordChr(password characters) property to * so that the password will appear as hidden characters * instead of the actual password. We have written the code so that both username and password must be correct to enable sign in if either one of them incorrect sign in will fail.

The Code

Private Sub OK_Click()
Dim username, password As String
 username = "John123"
 password = "qwertyupi#@"

If UsrTxt.Text = username And pwTxt.Text = password Then
 MsgBox ("Sign in sucessful")
ElseIf UsrTxt.Text <> username Or pwTxt.Text <> password Then
 MsgBox ("Sign in failed")
End If
End Sub

The Output

Figure 7.1

Figure 7.2

You can check out our animated passwords cracker program

Example 7.2

This example calculate the commission based on sales volume attained. Let's say the commission structure is laid out as in the table below:

Sale Volume($)Commission(%)
<5000 0
5000-99995
1000-1499910
15000-1999915
20000 and above20

In this example, we insert a textbox to accept sale volume input and a label to display commission. Insert a command button to trigger the calculation

The Code


Private Sub cmdCalComm_Click()
Dim salevol, comm As Currency
 salevol = Val(TxtSaleVol.Text)
  If salevol >= 5000 And salevol < 10000 Then
   comm = salevol * 0.05
 ElseIf salevol >= 10000 And salevol < 15000 Then
  comm = salevol * 0.1
 ElseIf salevol >= 15000 And salevol < 20000 Then
  comm = salevol * 0.15
 ElseIf salevol >= 20000 Then
  comm = salevol * 0.2
 Else
 comm = 0
 End If
 LblComm.Caption = Format(comm, "$#,##0.00")
End Sub

The Output

Figure 7.3

Example 7.3: Guess a Number Game

This is a guess a number game where the user key in a number and check whether the answer is correct. Thr program will provide a hint if the number is too small or too big. After a number of trial, the user should get the right answer. The program employ the If...Then...Else technique to check whether the entry is correct.

The Code
'Guess a Number
Const realNumber = 99
Dim userNumber As Integer

Private Sub EXit_Click()
 End
End Sub

Private Sub OK_Click()
 userNumber = entry.Text
  If userNumber > realNumber Then

  hint.Caption = "Your number is too big"
 ElseIf userNumber < realNumber Then
  hint.Caption = "Your number is too small"
 entry.Text = ""
 entry.SetFocus
Else
 hint.Caption = "Congratulation, your number is correct"
End If
End Sub

7.4 The IIf() Function

The IIf function denotes immediate decision function. It provides a simple decision making process based on three arguments, as follows:


      IIf(x, y, z)

x represents a logical expression while y and z represent a numeric or a string expression.

For example, the IIF(x>y, expression 1, expression 2) function evaluates the values of x and y, if x>y. then expression 1 is true, otherwise the expression 2 is true.

Example 7.3

Private Sub CmdNumeric_Click()
Dim x, y, a, b, ans As Double
 x = InputBox("Enter a number")
 y = InputBox("Enter another number")
 a = Val(x)
 b = Val(y)

 ans = IIf(a < b, b - a, a * b)
MsgBox ans
End Sub

Private Sub CmdString_Click()
Dim A, B, C As String
 A = InputBox("Enter a word")
 B = InputBox("Enter another word")
 C = IIf(A < B, A, B)
 MsgBox C
End Sub

Figure 7.4: The Interface

If you click test string and enter the first word long and the second word short, the logical condition is true, hence the word long will be displayed, as shown in Figure 7.5.

Figure 7.5

If you click test numeric and enter the first number 200 and the second number 40, the logical condition is false, hence the second expression will be executed, which is 20x40=800, as shown in Figure 7.6.

Figure 7.6


❮ Previous Lesson Next Lesson ❯


Copyright©2008 Dr.Liew Voon Kiong. All rights reserved |Contact|Privacy Policy