VB2022 VB2019 VB6 VB Sample Code About Us

Lesson 38 Creating Console App Part II


In this lesson, we shall learn how to create Visual Basic 2019 console applications using the If..Then...Else control structure and the Select Case control structure.

38.1 Using If....Then....Else

The  If...Then....Else structure is as follows:

If  conditions Then
     vb expressions
Else
     vb expressions
End If

Example 38.1

The following code uses If....Then....Else control structure to evaluate the answer entered by the user.

Sub Main()
Dim x, y, z, total As Single
Dim firstnum As String
Dim secondnum As String
Dim sum As String
firstnum = InputBox("Enter a Number")
secondnum = InputBox("Enter a number")
sum = InputBox("The answer is")
total = Val(firstnum) + Val(secondnum)
If total = Val(sum) Then
MsgBox("Correct")
Else
MsgBox("Wrong")
End If
End Sub

When we run the application, you will be presented with an input box as shown in Figure 38.1

figure38.1
Figure 38.1

After entering a number, you will be presented a second input box where you are required to enter the second number. After that, you will be presented with a third input box that prompts you to enter the answer which supposes to be the sum of the two numbers entered, as shown in Figure 38.2

figure38.1.2
Figure 38.2

If the answer is correct, a message box will display the word 'Correct', otherwise, it will show the word 'Wrong', as shown in Figure 38.3

figure38.1.3
Figure 38.3

38.2 Using Select Case

The Select Case control structure evaluates one expression for multiple values. Select Case is preferred when there exist multiple conditions.

The Select Case control structure is shown below:


Select Case expression

Case value1
        Block of one or more vb statements
   Case value2
        Block of one or more vb Statements
   
        .
   Case Else
        Block of one or more vb Statements

End Select

Example 38.2

This application allows the user to input an examination grade and it will display the result in a message box, as shown in the figures below:

figure38.2
Figure 38.4
figure38.3
Figure 38.5

The Code

Sub Main()
        Dim grade As String

        grade = InputBox("Enter Grade A, A-, B,C,D")
        Select Case grade
            Case "A"
                MsgBox("High Distinction")
            Case "A-"
                MsgBox("Distinction")
            Case "B"
                MsgBox("Credit")
            Case "C"
                MsgBox("Pass")
            Case Else
                MsgBox("Fail")
        End Select
    End Sub


❮ Previous lesson


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