Search Tools Links Login

VB6 Tutorial 17: If ... Then Blocks


There are many control flow blocks in Visual Basic 6 that help in executing some statements in a particular way. This lesson demonstrates the use of If-block.

The If control flow blocks provide a great way for decision making where one or more statements are executed depending upon a condition.

If-Then

In case of If-Then block, the condition is first checked. The condition can either be True or False. If it is True, the statements inside the If-Then block is executed. Otherwise, it does not execute the code in the If-Then block, the If-Then structure is skipped. It starts executing the statements just after the 'End if' phrase.

Syntax

If Condition Then
      statements
End If

Example

To check if the number is positive.

Dim num1 As Integer
num1 = 30
If num1 > 0 Then
    Print "The number is positive"
End If 

output: The number is positive.

See the attached project IfThen to see this in action.

Single Line version of If-Then

Single line and single statement

If a > 0 Then b = 1

Single line and multiple statements

If a > 0 Then b = 1: c = 2

If-Else

An If-Else block has two parts. If the condition is True then the first part is executed, otherwise the control goes to the second part and starts executing the lines of statements in the second part of the If-Else block.

Syntax

If Condition Then
    statements1
Else
    statements2
End If

If Condition is true then statements1 will be executed and if Condition is false, statements2 will be executed.

See the attached project IfThenElse to see how this block works.

Example

To print the largest number.

Dim num1 As Integer, num2 As Integer
num1 = 30
num2 = 50
If num1 > num2 Then
    Print num1
Else
    Print num2
End If

Output: 50

The attached project LargestNumber allows you to see how If / then / else works with real data.

Single line version of If-Else

If a > 0 Then b = 1 Else b = 0

In the next lesson, you'll learn more about the if-else statements.

About this post

Posted: 2018-04-01
By: vb6boy
Viewed: 517 times

Categories

Visual Basic 6

VB6 Tutorial

Attachments

LargestNumber.zip
Posted: 4/1/2018 12:16:20 PM
Size: 1,258 bytes

IfThenElse.zip
Posted: 4/1/2018 12:16:07 PM
Size: 999 bytes

IfThen.zip
Posted: 4/1/2018 12:15:03 PM
Size: 995 bytes


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.