Understanding if statements and conditionals

Level:
Level1

This tutorial explains in depth how Visual Basic 6 handles conditional (if) statements and different loops. It goes very in depth so if this is your first time programming, it may be a little advanced. Just try to understand as best you can and as you learn more it will make more sense. 

Overview

Up until now, you have learned how to develop VB6 applications that store values, perform mathematical computations on these values, and display the results of these computations--all of which is swell and dandy, but no more useful than your average calculator. What if you want, for instance, to determine if a number is odd, to find the factorial of a number, or to generate the Fibonacci Series? None of these tasks can be done through simple arithmetic, but rather they require something known as control structures.

Control structures in Visual Basic take two primary forms: if-statements and loops. With an if-statement, you can evaluate an expression, and perform one task if that expression is True and perform another if it's False. This allows your program to respond differently to different values and inputs, which allows for far more advanced calculations and a far wider range of possible behaviors. Loops, on the other hand, allow you to repeat the same task a given number of times, making it possible to go far beyond basic arithmetic to achieve goals such as calculating the Fibonacci series.

Logical Expressions and Operators

Before we can proceed to learning about if-statements, we must first learn about logical expressions in Visual Basic. In Variables and Types in VB6 you learned about a type of variable called a Boolean, which has only two possible values: True and False. A Boolean value can be defined explicitly using bl = True, but this usage of Booleans is rare and not particularly useful. The more common application of a Boolean is in evaluating a logical expression, any expression which can be evaluated as either True or False.

A typical logical expression in Visual Basic takes the following form: = P Q. P and Q can be either constants, variables, or logical expressions themselves. The is a logical or comparative operator, anything that performs a comparison between P and Q and returns a Boolean value. Here's an example of a logical expression in Visual Basic:

Public Sub Main()
   Dim B As Boolean
   Dim P As Integer, Q As Integer
   
   P = 5
   Q = 7
   B = (P = Q)
   
   MsgBox B
End Sub

In this example, we used the logical operator of equality, denoted by the "=" sign. This operator returns True if P is equal to Q and False if it does not. In this example, B is False because P (5) does not equal Q (7). The parentheses, though not needed, are placed around P = Q to make clear that this is a logical expression, rather than some form of assignment.

Now, let's take a look at a few other logical operators in Visual Basic. Please note that these are not anywhere near all of the comparison and logical operators available in Visual Basic, but they are the ones you'll use most frequently.

Comparison Operators

The following operators are all comparison operators, meaning that they compare one expression to another and return a Boolean. They are all overloaded, meaning that their left-hand and right-hand expressions can be of (almost) any type.

Equality "="

As you saw in the example above, the equality operator is denoted by an equals sign ("="). This operator can be quite confusing because it is both an assignment operator and a logical operator. The distinction between whether it is acting as a logical or an assignment operator is made solely upon context--if a line begins with a variable, followed by an equals sign, followed by an expression, then the equals sign is treated as an assignment operator, meaning that the value of the following expression is written to the variable. If it is found anywhere else in a program, then it is treated as a logical operator.

Syntax: P = Q
Returns: True if P is equal to Q, and False if it is not.

Inequality "<>"

This operator is synonymous with: (P = Q) = False. In this format, (P = Q) is the left hand expression, and False is the right hand expression, which is evaluated for equality. If (P = Q) is True, then (True = False) is false, but if (P = Q) is True, then (True = True) is True.

Syntax: P <> Q
Returns: True if P is not equal to Q, and False if P is equal to Q.

Greater Than ">"

Syntax: P > Q
Returns: True if P is greater Q, and False if P is less than or equal to Q.

Less Than "<"

Syntax: P < Q
Returns: True if P is less than Q, and False if P is greater than or equal to Q.

Greater Than Or Equal To ">="

Syntax: P > Q
Returns: True if P is greater than or equal to Q, and False if P is less than Q.

Less Than Or Equal To "<="

Syntax: P < Q
Returns: True if P is less than or equal to Q, and False if P is greater than Q.

Logical Operators

The following operators are logical operators that can take only Boolean values as arguments; this means that both P and Q can each be only true or false. Keep in mind that the evaluation of every logical expression returns a Boolean, thus P and Q can also be logical expressions.

While this lesson will not go into this in depth, all of these operators can also be used as bitwise operators, in which case they do not require that the expressions be Boolean, nor do they truly return Boolean. For the time being, please only use them as logical operators, as it will save you many headaches.

Negation "Not"

This operator does not take the standard form of P Q. Instead it is a single-argument operator, that takes only one Boolean expression. The negation operator ("Not") quite simply returns the opposite of the given Boolean expression--it is synonymous with (P = False).

Syntax: Not P.
Returns:

P Not P
True False
False True

 

Conjunction "And"

The Conjunction operator ("And") takes two or more Boolean expressions and returns true iff both expressions are True.

Syntax: P And Q
Returns:

 

P Q P And Q
True True True
True False False
False True False
False False False


Disjunction "Or"

The Disjunction operator ("Or") takes two or more Boolean expressions and returns true if any of them is True.

Syntax: P Or Q
Returns:

P Q P Or Q
True True True
True False True
False True True
False False False

Exclusive Disjunction "Xor"

The Exclusive Disjunction, also known as "exclusive or", operator ("Xor") takes two Boolean arguments and returns true if one, and only one, of them is True.

Syntax: P Xor Q
Returns:

P Q P Xor Q
True True False
True False True
False True True
False False False

If-Statements

As you learned about in Control structures, the If-Then statement is the most simplistic and widely used form of flow control. In short, an If-Statement evaluates a logical expression, performs one task if that expression is True, and does either nothing or performs a seperate task if it is False. And so how do we write one in Visual Basic?

If-Statements in both VB6 and BASIC fall under three categories: the simple If-Then statement, the If-Then-Else statement, and the If-Then-ElseIf statement. If-statements may be nested inside of any other control block, including inside of other If-Statements. Nesting will be covered in depth later.


The If-Then Statement

VB6 uses the same simplistic and easily comprehendible syntax for If-Then Statements as BASIC. The If-Then Statement can be written two ways:

If (Expression) Then  (Line of  code to execute)

--OR--

If (Expression) Then
   (Multiple lines of code to execute)
End If

The (Expression) parameter can be any Boolean value or logical expression. If the code you want to execute when (Expression) is True can fit on one line, then you can write the entire If-Then statement on one line with no enclosing "End If".

The If-Then-Else Statement 

But now what if you want certain code to be executed when the expression you are evaluating is true and certain code to be executed when the expression is false? You could of course write:

If a Then MsgBox "A is True!"
If Not a Then MsgBox "A is False!"

 

But instead of having to write that every time, VB6 provides an additional "Else" clause for your If-Statements. The usage is very simple:

If (Expression) Then
    (Code to execute if True)
Else
    (Code to execute if False)
End If

One Step Further: ElseIf 

Okay, so now that you can perform two different actions depending upon a variable's state, but what if that's just not enough? That's why VB6 also has an ElseIf statement, which has the following syntax:

If (Expression1) Then
    (Code to execute if Expression1 is True)
ElseIf (Expression2)
    (Code to execute if Expression1 is False and Expression2 is True)
ElseIf (Expression3)
    (Code to execute if Expression1 and Expression2 are False, but Expression3 is True)
Else
    (Code to execute if neither Expression1, Expression2 nor Expression3 is True)
End If

You can use as many Else-If statements as you want, though you may have no more than one Else statement for every If statement.


Examples 

So now that we know everything we need to know to begin using If-Statements in our code, let's look at some examples.

Public Sub Main()
   Dim S1 As String, S2 As String
   S1 = "Foo"
   S2 = "BAR"

   Dim X As Integer
   X = 0

   If X < 5 Then Debug.Print "X is less than 5"
   
   If X > 3 Then
       Debug.Print "X is greater than 3."
    Else
      X = 3
      Debug.Print "The value of X was changed from 0 to 3"
    End If
   
   If S1 = "FOO" Then
      If S2 <> "BAR" Then
         Debug.Print "S2 is not BAR."
      ElseIf (X > 0 And X <= 3) And (S2 = "BAR") Then
         Debug.Print "X is greater than 0 and less than or equal to 3, and S2 = 'BAR'."
      ElseIf X = 3 Then
         Debug.Print "X is 3 and S2 is not BAR."
      Else
         End
       End If
    End If
End Sub

This tutorail is released under the GNU Free Documentation License 1.2. The original can be found here.

If you enjoyed this post, subscribe for updates (it's free)

can't run

Private Sub cmdCalculate_Click()
Dim Radius As Double
Dim Density As Double

'ead values from the text boxes

Weight = Val(txtWeight.Text)
Radius = Val(txtRadius.Text)
Radius = Radius * 10 ^ (-9)
Density = Val(txtDensity.Text)
dbNa = 6.022E+23

If Density = ((4 * Weight) / (((4 / (3 ^ 1 / 2)) * Radius) ^ 3 * dbNa)) * 10 ^ (-6) Then
Msg "Crystal is FCC"
ElseIf Density = (2 * Weight) / (((2 / (2 ^ 1 / 2) * Radius) ^ 3 * dbNa)) * 10 ^ (-6) Then
Msg "Crystal is BCC "
ElseIf Density = ((1 * Weight) / ((2 * Radius) ^ 3 * dbNa)) * 10 ^ (-6) Then
Msg "Crystal is SC "
Else
End
End If
End If
End Sub
when i click the button the error saying "compile error: Sub or Function not defined'.....so please help me

can't run

Private Sub cmdCalculate_Click()
Dim Radius As Double
Dim Density As Double

'ead values from the text boxes

Weight = Val(txtWeight.Text)
Radius = Val(txtRadius.Text)
Radius = Radius * 10 ^ (-9)
Density = Val(txtDensity.Text)
dbNa = 6.022E+23

If Density = ((4 * Weight) / (((4 / (3 ^ 1 / 2)) * Radius) ^ 3 * dbNa)) * 10 ^ (-6) Then
Msg "Crystal is FCC"
ElseIf Density = (2 * Weight) / (((2 / (2 ^ 1 / 2) * Radius) ^ 3 * dbNa)) * 10 ^ (-6) Then
Msg "Crystal is BCC "
ElseIf Density = ((1 * Weight) / ((2 * Radius) ^ 3 * dbNa)) * 10 ^ (-6) Then
Msg "Crystal is SC "
Else
End
End If
End If
End Subwhen i click the button the error saying "compile error: Sub or Function not defined'.....so please help me

Help me with this problem please. :(

The amount of miscellaneous fees a student pays during enrollment is determined by his nationality, year level and gender.
A flat fee of 200php is paid by all students.
'Male seniors pay additional 100php for CMT.
'Female freshmen and sophomores pay an additional 75php for Girl Scouting.
'Foreigners pay an additional 200php for alien fees.

Make a program that would input NATIONALITY(1 for Filipino, 2 for Foreigner), GENDER ( 1 for Male, 2 for Female), and YEAR LEVEL (1-4) and output MISCELLANEOUS FEE.

Thanks a lot.

Just change the design. Sure thing is MY Code Works!

#include
#include

void main()
{

int mis=0,nation;
char gender;

printf("\nWhat is your Nationality?[1-Fili]/[2-For]");
scanf("%d",&nation);
printf("\nEnter Gender:[M-Male]/[F-Female]");
fflush(stdin);
scanf("%c",&gender);

if(nation==1)
{
mis+=200;
}
else if(nation==2)
{
mis+=400;
}

switch(gender)
{
case 'm':
case 'M': mis+=100; break;
case 'f':
case 'F': mis+=75; break;
}

printf("\nYour Total Miscellaneous Fee is: %d\n",mis);

getch();

}

All the tutorials leading up

All the tutorials leading up to this one were wonderful and thoroughly explained and easy to understand. This one you bring in so many terms you do not define and just all together this specific tutorial is confusing. Please rewrite this one.

not getting the last example

really ia am not getting the last can u explain me that example pleaseeeeee

I'm an advanced user and

I'm an advanced user and have taught several languages including VB. After reading some of the comments I have to reply, I've only looked as some section of the tutorial but all I have seen are very good. I can see how someone not wanting to take the time to study might have problems but all and all, very nice writing.

debug.print?????

i m nt able to understand, what debug.print is...
plz help me... m waiting...

This section of the tutorial

This section of the tutorial confuses me. I think I'll skip it for a while.

?

What is 'Public Sub Main()'? When did that come to use? I don't understand.

Answer to What is 'Public Sub Main()'? When did that come to use

That statement is used to determine which function are you using.
If it is the form, the label, the textbox, etc.

Horrible Guide

Seriously? I've googled like 20 terms reading your guide that weren't explained thoroughly and half of your examples have nothing to do with the actual code you were trying to teach in the first place. A very inadequate guide for beginners and insufficient for my needs as I'm sure it is for others.. I'm assuming this guide was just made by an idiot using big words and am hoping that the rest are as good as the first few and not similiar to this garbage. Sorry for the rant, but after reading this over and over for about 2 hours trying to figure out what the hell you were attempting to teach, I dove into c++ and learned on my own... Still unsure as to why my code isn't working, I did it exactly as you instructed but your example after the instructions didn't include a single boolean? How do I go step by step from a random mess of coding?

I agree what a bunch of

I agree what a bunch of poepols

No way!

I think you should get your eyes checked, dude! This guide is really cool, and one of the best I have seen on the net.

HELP

I am new to vb6. actually i'm having a problem using the "Debug.Print" thing. It really doen't show anything.. can you please help me. thanks

I just noticed...

I just clicked on my lil button that does this, And I figured out what Debug.Print does. Its the little Immediate box that appears at the bottom. :D

how can i replace all the

how can i replace all the spaces in a text with the "~" symbol? is there any exact code?

Public sub main() ?

The examples in this guide start to use the term "Public Sub Main()" as a pose to "Private Sub Form_Load()" which was used in all previous tutorials, what does this mean?

I have an answer to your

I have an answer to your question. Private Sub Form_Load()" is for a particular form. In this case, any code in this sub will be loaded when the form is loaded. Public Sub Main()" is creating a sub. This would usually not go into a form, but in someplace else, like a mod. Let me explain a little.

If you were to put

Private Sub Form_Load()
MsgBox "Hello, World!"
end Sub

When your program loads, the message box will pop up.

If you were to add a command button to the form, and delete the MsgBox "Hello, World!"
you create a module, in it add "
Public sub Main()
MsgBox "Hello, World!"
end sub
"
Then you double click on the command button and add in
call Main

It would only pop up with the message box when you click on the button. This helps when you want to use the same sub on multiple forms.

Public sub main() ?

The examples in this guide start to use the term "Public Sub Main()" as a pose to "Private Sub Form_Load()" which was used in all previous tutorials, what does this mean?

Not Showing

Where should I put the Debug.Print commands to?
I put it to a Button, Form,...
But It's Not showing:

Debug.Print X

same here:(

debug.print is'nt working...

uh help?

1) hey sorry but i tried figuring out the code of calculating Fibonacci Series, but i couldnt get the loop down right. i need to know how to use the same variable for two values so the program will add the previous two numbers starting from 0 and 1.

2) secondly, im making a probram in vb6 that will solve any matrix for me. i used the same system as that of excell as my variables (a1, a2, a3, a4, b1, b2, b3, b4, ect.) and i also want it to calculate using Cramers Rule when necessary. also, if the user leaves a text box empty, it doesnt do the calculation because of the dimentions, i need it to treat an empty textbox as 0. i tried using the "NullOrEmpty" command but it doesnt work because of something in my calculation code. i cant figure out what. please help!!

thnx for ur time...:) plz respond!!!!!!

I'm not fully understand but it nice work

I will leave that lesson for while and i will back to it after few lessons forward

thanks

please help

i made a database(microsoft access v.7.0) named password, now i made a design on how to check if the username is match with the password but i cannot code it.... i used data in the toolbar..

Private Sub cmdok_Click()
If Len(txtpassword) = 0 Or Len(txtusername) = 0 Then
MsgBox "Password did not match USER NAME", vbOKOnly, "PASSWORD ERROR"
'txtpassword.SetFocus
Exit Sub
End If

Do While Not dtapassword.Recordset.EOF

If txtusername.Text = dtapassword.Recordset("username") Then

found = True

ElseIf txtpassword.Text = dtapassword.Recordset("password") Then

MsgBox "WELCOME " + txtusername.Text, vbOKOnly, "WELCOME"

frmlog.Hide
Load frmmenu
frmmenu.Show
frmmenu.SetFocus

Else

MsgBox "Password did not match USER NAME", vbOKOnly, "PASSWORD ERROR"
txtpassword.SetFocus

End If

Exit Do

Else

dtapassword.Recordset.MoveNext
found = False

End If

Loop
MsgBox "tae"
'If found = False Then

MsgBox "You are not an Authorize Person", vbOKOnly, "LOGIN ERROR"
txtpassword.SetFocus
dtapassword.Refresh
'Exit Sub

End If

Exit Sub

this is my code.. please help me to code a simplier code

MAke It Simple

Private Sub cmd(name of your command)_Click()
|-------> change the name of your cmd button in its properties, cmd first
Ex. cmdLen

If Text1.Text = "Len" Then GoTo Text2

Else
Unload Me
MsgBox "Wrong Username"

If Text2.Text ="Tae"
Unload Me
Menu.Show
Login.Hide

Else
MsgBox "Wrong Password, Access Denied"

End If
End Sub

Hope it could help

More details

Can you give more details such as what the error is when you try to run the code. What happens. What line the error occurs on...

starting to lvoe you XD

Hi, i am really new to this, i have noone to hlep so i start reading some tutorials, and i am loving it ;D pretty cool. i have done all you said and i did it rigth, but now, in this toturial, i can't, just don't know why. This is my code:
Private Sub Command1_Click()
Public Sub Main()
Dim S1 As String, S2 As String
S1 = "Foo"
S2 = "BAR"
 Dim X As Integer
   X = 0

   If X < 5 Then Debug.Print "X is less than 5"
   
   If X > 3 Then
       Debug.Print "X is greater than 3."
    Else
      X = 3
      Debug.Print "The value of X was changed from 0 to 3"
    End If
   
   If S1 = "FOO" Then
      If S2 <> "BAR" Then
         Debug.Print "S2 is not BAR."
      ElseIf (X > 0 And X <= 3) And (S2 = "BAR") Then
         Debug.Print "X is greater than 0 and less than or equal to 3, and S2 = 'BAR'."
      ElseIf X = 3 Then
         Debug.Print "X is 3 and S2 is not BAR."
      Else
         End
       End If
    End If
End Sub
When i click on the button, it show a error box sayng:"Compiled Erros: Expected End Sub" Don't know why? Is the End Sub is a wrong place? =S sorry, started yesterday XD thx a lot ;D will wait for answer

2 Subs

Lol it's happening because you have 2 Starter subs, but only 1 End sub.

Solution

you have 2 subs started in the first 2 lines of your code, but only close one at the end of your program
insert a new line under line 1, and insert "End Sub". That should clear it up for you.

-DT

hey

Private Sub command1_click()
Dim S1 As String, S2 As String
S1 = "FOO"
S2 = "BAR"

Dim X As Integer
X = 0

If X < 5 Then Print "X is less than 5"

If X > 3 Then
Print "X is greater than 3."
Else
X = 3
Print "The value of X was changed from 0 to 3"
End If

If S1 = "FOO" Or S2 <> "BAR" Then
Print "S2 is not BAR."
End If
If (X > 0 And X <= 3) And (S2 = "BAR") Then
Print "X is greater than 0 and less than or equal to 3, and S2 = 'BAR'."
ElseIf X = 3 Then
Print "X is 3 and S2 is not BAR."
Else
End If
End Sub

problem with the Inequality sign <>

Im trying to write off an if statement that will flag when the value of the cell does not equal one of the correct values (1 or G).

~i wont go through writing my whole code, but this is basically what i have:

For j = 7 To LastRow
For i = 3 To 3
Cells(j, i).Select
ActiveCell.Formula = ActiveCell.Value
If ActiveCell.Value <> "G" Or ActiveCell.Value <> "1" Then
Rflag = 1
Comm = "Cell must be G or 1"
Cmnt (Comm)
End If
Next i
Next j

*j, i, and LastRow are all longs, and LastRow is defined as a sub later.

the result i get is the cells being flagged with the coment even when the value is G or 1. Any ideas?

The answer is quite simple:

The answer is quite simple: the expression in your if statement is wrong, the correct one would be:

If ActiveCell.Value <> "G" And ActiveCell.Value <> "1" Then

why is that? because you only want to flag the cell if it is neither 1 or G.
if you use "Or" then the expression evaluates to True with 1 (because it is not G) as well as with G (because it is not 1).

hope that helps,
marcus

vc

vc

Possible spaces?

Is there possibly spaces in the cell as well? i.e. is ActiveCell.Value = "G "? Try putting a MsgBox "Here is value:[" + ActiveCell.Value + "] right before your if statement. That will help you see. If this is the problem you can use the trim function to get rid of any spaces.

Nice job

Nice Job!
:)
now im going to read it all to the end....
use form actions, button actions, etc....

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. The supported tag styles are: <foo>, [foo].

More information about formatting options

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.