Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

Visual Programming

The concept of computer programming


Before we begin Visual Basic 6 programming, let us understand some basic concepts of
programming. According to Webopedia, a computer program is an organized list of
instructions that, when executed, causes the computer to behave in a predetermined
manner. Without programs, computers are useless. Therefore, programming means
designing or creating a set of instructions to ask the computer to carry out certain jobs
which normally are very much faster than human beings can do.

A lot of people think that computer CPU is a very intelligent thing, which in actual fact it is
a dumb and inanimate object that can do nothing without human assistance. The
microchips of a CPU can only understand two distinct electrical states, namely, the on
and off states, or 0 and 1 codes in the binary system. So, the CPU only understands a
combinations of 0 and 1 codes, a language which we called machine language. Machine
language is extremely difficult to learn and it is not for us laymen to master it easily.
Fortunately , we have many smart programmers who wrote interpreters and compilers
that can translate human language-like programs such as BASIC into machine language
so that the computer can carry out the instructions entered by the users. Machine
language is known as the primitive language while Interpreters and compilers like Visual
Basic are called high-level language. Some of the high level computer languages beside
Visual Basic are Fortran, Cobol, Java, C, C++, Turbo Pascal, and etc

What is Visual Programming?

Visual Programming provides the user with an interface that is intuitive and easy to use. In
developing such an interface, the programmer needs to use the user friendly features like
windows, forms, menus, buttons, and list boxes and so on.

A visual programming environment provides all the features that are required to develop a
graphical user interface as ready-to-user components. The programmer does not have to write
code to create and display commonly used user-friendly components each time around.

In visual programming, when a certain component or feature as button is needed, then the
programmer just need to drag-and-drop the ready-to-use component from the toolbar to the Form
window. They can simply add more, resize, move and rename the component for programmers
ease. Typically a mouse is used to select and place the necessary component. Thus, the visual
programming environment is also called a point and click environment.

Visual programming enables attaching the same codes for the similar kinds of components. For
example in calculator, using of control arrays of components to handle the click event of the
digits.

1
Some popular visual programming tools are:

 Visual Basic
 PowerBuilder
 Delpi
 Visual C++
 Developer 2000

What is Visual Basic?


What Is Visual Basic and Why do I need it?
So what is Visual Basic? "Visual" refers to the method used to create what the user sees—the
graphical user interface, or GUI. "Basic" refers to the BASIC (Beginners All-Purpose Symbolic
Instruction Code) programming language,

VISUAL BASIC is a high level, VISUAL and events driven Programming Language

Visual Basic is the most widely used programming language for creating Windows applications
and games. Why? Because it's easy to learn, and doesn't require you to memorize difficult
commands like other programming languages.

Visual Basic suit more for application developing than for Games developing.
You can create sophisticated games using Visual Basic, But
If you want to make a really advanced professional game like Quake 2,
You may choose other language (like C++), that would be much more
harder to program with.
However, Visual Basic will be probably powerful enough to suit all your application
and games programming needs.

Advantages of Visual Programming (VB).

Visual programming enables:

1. Visual development of graphical user interface which are easy to use and easy to learn.
2. Eliminates the tradition of writing of code to display the required components.
3. Facilitates to use the ready to use components. The programmer picks up the required
components from this list to display it.

2
4. The component can be moved, resized and even deleted, if so required.
5. There is no restriction on the number of controls that can be placed on a form.
6. The interface components provided by the visual programming environment have some code
built into them to handle events generated during the run state.
7. Because Visual Basic is so popular, There are many good resources (Books,
Web sites, News groups and more) that can help you learn the language.
You can find the answers to your programming problems much more easily
than other programming languages.
8. You can find many tools (Sharewares and Freewares) on the internet that will
Spare you some programming time.
For example, if you want to ping a user over the internet in your program,
Instead of writing the ping function yourself, you can download a control
that does it, and use it in your program.
Compare to other languages, Visual Basic have the widest variety of tools
that you can download on the internet and use in your programs.

Disadvantages of Visual programming (VB)

When visual programming makes it very simple to create complex user interfaces, it suffers from
some disadvantages:

1. As the name implies, the entire process of developing an application using a visual development
environment is visual. Thus, the development environment in itself is highly graphical in nature
and therefore requires more memory.
2. Computer supporting the video graphics system with high performance is required.
o Larger capacity hard disk.
o More RAM.
o Faster Processor.
3. Visual programming can be done only with GUI operating systems as Windows.
4. Visual Basic is powerful language, but it's not suit for programming really
sophisticated games.

Hardware and software considerations for visual programming


SOFTWARE:

Microsoft Visual Studio

Windows XP (Any Service Pack)


MS Access 2003 or Higher

HARDWARE:

3
Hardware Requirements

* 200 Mhz Processor


* 128 Mb RAM or Higher
* 100GB SATA (Serial Advanced Technology Attachment) Hard Drive
* 5400 RPM hard disk drive
* DirectX 9 capable video card running at 1024 x 768
* DVD-ROM Drive

TERMS…..

Getting Started
Note that all the images in this tutorial taken from Visual Basic version 6.0.
If you using other version of Visual Basic, the images that you will see may
be a little different.

Run the Visual Basic program. The first thing you see is:

Figure 1

4
Here you choose what is the kind of the program you want to create.
For creating a simple Visual Basic program, choose the Standard EXE,
and press the Open Button.

(If Figure 1 is not the first thing you see when you run Visual Basic,
choose from the Visual Basic menu File->New Project (Figure 2))

Figure 2

5
After you've clicked the Open button, you will see:

Figure 3

6
Getting Started (Continue)
Look at the form with the title bar Form1.
This is how your program will look like.
Everything you will place on this form will appear in your program.
As you can see, your form is currently empty.
You didn't program anything yet, but lets run the program!

Click on the Play button in the toolbar (Figure 4)

Figure 4

Now your program is running (Figure 5):

Figure 5

As you can see, the form is empty.

7
You can move the form, minimize and maximize it.

To stop the program from running, you can click on the Stop button
in the Toolbar (Figure 6), or click the form's X button (Figure 7).
It's very recommended that you will always close your programs using the
form's X button instead of the Visual Basic Stop button.
It's like shutting Windows From the Start button, instead of Pressing
the Power button.

Figure 6

Figure 7

Learning about Properties


Every component (form is component for example) has properties,
that determine its look and its functioning.
Properties can be the component color, width, height and more.

To see the form properties, select from the menu View->Properties Window (Figure 8).

Figure 8

8
The properties window looks like this:

Figure 9

9
In the red circle you can see the component name:
These are the properties of a Form, and the form's name is Form1.

The column marked by the blue circle contains the form's properties names:
The form has Name property, Appearance property AutoRedraw property, and more.

The column marked by the black circle contains the form's properties values:
The form's Name is Form1, The form's Appearance property is 1 - 3D, and so on.

You can change the form's properties.


For example, lets change the form's Caption property.
What is the Caption property? The Caption is the text that appears on the
Form's title bar.
Right now the text that appears on the form's title bar is Form1 (Figure 5).

To change the Caption property, simply click on the Caption property in the
form's properties names column (Figure 10).

Figure 10

As you see, the current Caption is Form1.


Delete the "Form1" text and type instead of it "Hello" (Figure 11).

Figure 11

10
Now run the program using the Play button (Figure 4).
You will see that the text on the form's Title bar is Hello (Figure 12).

Figure 12

Try to change others properties:


Change the form's BackColor property to change the form's background color,
Change the Icon property to change the icon that appears on the form's title bar.
You can try and change every property, and in this way learn what does it do.

Adding Controls to the Form


There are many controls you can use with your program:
Buttons, Text Boxes, Pictures, Scroll Bars and more.
You can see all these controls in the Toolbox.
To see the Toolbox, Select from the menu View->Toolbox (Figure 13).

Figure 13

11
And you will see the Toolbox (Figure 14):

Figure 14

12
Now lets add a button to your form.
Buttons in Visual Basic called "Command Buttons".
To add a button, click on the Command Button icon in the Toolbox (Figure 15).

Figure 15

As results, the Command Button icon will look pressed (Figure 16).

Figure 16

13
Now click on the form with the left mouse button, and hold the button
down while moving the cursor.
You will see a rectangle.
Release the mouse button, and in the place of the rectangle you
will see a button (Figure 17).

Figure 17

Changing the button's Properties


Now you have a button on your form.
You can change its location by dragging it, and change its
size by dragging the Blue Hot Spots that found on each one of its conrners.

Run the program by clicking the Play button.


You can see that you have a button on your form, that you can click on it,
But it still doesn't do anything.

To see the Command Button's Properties window, click on it with


the right mouse button and select Properties for the pop-up menu (Figure 18).

Figure 18

14
The Command Button's Properties window (Figure 19):

Figure 19

As you can see, In the top of the properties window, right under the title bar,
appears "Command1 CommandButton".

Command1 - because it's the name of this specific Command Button (look
at the name property).

CommandButton - because this is this component type.

15
Note that two components can't have the same name.
If you will add another Command Button to your form, its name will
be "Command2" by default.

If you want you can change the Name of any component, by simply
changing the component's Name property.

Now lets change the Command Button's Caption property.


The caption property is the text that appears on the Command Button.
Change the Caption property to "Click Here", and you will see that
"Click Here" appears on your Command Button.

Change the Command Button's BackColor property to blue (or other color).
The change won't take affect, untill you will set the Command Button's Style
property to 1 -Graphical.

You can now play a little bit with the Command Button's properties,
this is the best way to learn what every property does.
You can also add other controls from the Toolbox to your form,
And play around with their properties.

Learning about Events


Visual Basic is "Event Driven" language.
What does it mean?

Everything that happening, launch an event.


You've moved the mouse? The "MouseMove" event has been launched.
You've pressed a key? The "KeyPress" event has been launched.

You can program the events.


When the mouse moves, you can change the Form's color (for example),
and when a key is pressed, You can play a MP3 file.

To start programming the events, double click on the form.


You will see the "Code Window" (Figure 20).

Figure 20

16
The Code Window opened with the Form_Load event.
The Form_Load event occurs when the form is loaded, and this happening
when you start the program.
So the code that you will enter to the Form_Load event will be launched
when the program is being started.

The code that belongs to the Form_Load event should be placed


between Private Sub Form_Load() and End Sub

The Form_Load event should look like this:

Private Sub Form_Load() (The beginning of the Form_Load event)


This is the code that belongs to the Form_Load event
End Sub (The end of the Form_Load event)

Learning about Events (Continue)


Lets program the Form_Load event.

"MsgBox" is Visual Basic command that launch a message box.


for example, the line:

MsgBox "Hello"

Will launch a message box with the text "Hello".

Insert the line MsgBox "Hello" to the Form_Load event (Figure 21).

Figure 21

17
Now run your program using the Play button.
When the program is started, a message box with the
text "Hello" is appear (Figure 22).

Figure 22

More Events
The Form has more events besides the Form_Load event.
How can you find them?

Click on the Drop-Down List that found in the upper left corner of
the Code Window, where appears right now the text "Form" (Figure 23).

Figure 23

18
You will see a list of the components that found in your program.
You have 1 command button with the name "Command1" and 1 Form.
Here you select which component's event you want to program.
We want to program a form's event, so select "Form" from the list (Figure 23).

Which events the form has?


Click on the Drop-Down List that found in the upper right corner of
the Code Window, where appears right now the text "Load" (Figure 24).

Figure 24

You will see the complete list of the form's events:


Load, LostFocus, MouseDown, MouseMove and more.

Lets program the Form_Unload event.


Select "Unload" from the form's events list.
The Form_Unload event occurs when the form is being unloaded,

19
and this happening when you close the program (Using the form's X button (Figure 7)).
So the code that you will write in the Form_Unload event will be launched
when you close the program.

Insert the following line to the Form_Unload event:

MsgBox "GoodBye"

After you've inserted this line to your Form_Unload event,


the Form_Unload event should look like this:

Private Sub Form_Unload(Cancel As Integer)


MsgBox "GoodBye"
End Sub

Run the program.


When the form is being loaded at the very start, The Form_Load event
is being executed and a message box with "Hello" text is popping.
When you close the program by clicking the form's X button, the Form_Unload
event is being executed and a message box with "GoodBye" text is popping.

The Command Button's Events


Now lets program some of the Command Button's events.
Select "Command1" from the components list (Figure 23).
Check which events the Command Button has by clicking
the Events list (Figure 24).

We want to execute a code when the user is clicking on the button,


So lets program the Command Button's Click event.
Select "Click" from the Events list.
Insert the following line to the Click event:

MsgBox "You have Clicked on the button!"

After you inserted this line to the Click event the Click event should look like this:

Private Sub Command1_Click()


MsgBox "You have Clicked on the button!"

20
End Sub

As you can see, the Command Button's Click event called "Command1_Click",
because the name of the specific Command Button that we program
its Click event is "Command1".
If we had program the Click event of a Command Button with the
name "BlahBlah7", the Click event would be called "BlahBlah7_Click".
Every component has its own unique events, therefore if you had
5 Command Buttons on your form, every one of them has its
own unique Click event.

Run the program, and click the button.


When you clicking the Command Button with the
name "Command1", The Command1_Click event is being
executed, and a message box with the text "You have Clicked on the button!"
is popping.

The Command Button's Events (Continue)


To learn about more events, we will use the "Print" command.
The "Print" command simply writing a text on the form.
For example, the following line:

Print "Hello"

Will write "Hello" on the form (Figure 25)

Figure 25

21
Add another Command Button to your form.
The New Command Button's name is "Command2" by default (Figure 26)

Figure 26

Now, rewrite the Command1 Click event and insert the


following line to it:

Print "This is Command1"

Select "Command2" (This is the name of the second


Command Button) from the Components list (Figure 23),
And select "Click" from the Command2 events List.

Enter the following line to the Command2_Click event:

Print "This is Command2"

After you've done so, your code should look like this:

Private Sub Command1_Click()


Print "This is Command1"
End Sub

Private Sub Command2_Click()


Print "This is Command2"
End Sub

22
Run the program.
When you are clicking on Command1 Button, the text "This is Command1"
appears on the form, and when you are clicking on Command2 Button,
the text "This is Command2" appears on the form.

Learning about Variables


Using Variables is one of the most basic and important subjects
in programming, so this lesson is very important.

Variables are destined to save data.


You can save in variable Text or number.
For example, you can have one variable that holds the Text "Hello and Goodbye",
and have another variable that holds the number 623882

You can think about variables as a cabinet's drawers.


Every drawer has a sticker on it with its unique name.
You can put in each one of the drawers one number or one text String.
During your program, you can open the drawer with the sticker "TheUserName"
and get the text string that found inside the drawer.
You can also delete the text string that found inside the drawer
and put instead of it other text string.

Right now, we are going learn about 2 variable types.


The first type called Integer.
Integer variable can store an Integer number (round number without any fraction)
between -32,768 to 32,767.

You can store in Integer variable the number 0 or the number 375 or
the number -46, but you can't store the number 4.5 (Because of the .5)
or the number 100,000 (Because It's bigger than 32767) or the
number -50,042 (Because it's smaller than -32,768)

The second type called String.


You can store in String variable any text that you want.
For example "Hello" or "abcDDefGhIjk123456 blah blah %$#@!??? Blah!"

Working With Integers


The process of creating variable called "Declaring"

23
To Declare (=create) Integer variable simply write:

Dim MyTest As Integer

What does the line above do?


It creates an Integer variable with the name MyTest.

Dim = Declare
MyTest = the name of the new variable
As Integer = The new variable type will be Integer.

Now you can put a number inside this variable.


You can do that by simple write:

MyTest = 10

The line above will insert the number 10 into the MyTest variable.
Now the MyTest variable stores the Number 10, but how
can you access this value from your program?
You can do that using the variable name. Example:

Print MyTest

The line above will write 10 on the form.


Pay attention to the differents between

Print MyTest

and

Print "MyTest"

Where you putting a text inside quotes (Like in the bottom line),
Visual Basic treat it as a Text, and will print it As-Is.
The Print "MyTest" Line will print MyTest on the form.

Where you putting a text Without quotes (Like in the upper line),
Visual Basic treat it as a variable name, and will print the value that found
in the variable.

24
The Print MyTest Line will print the value that found in
the MyTest variable, therefore it will print 10 on the form.

Working With Integers (Continue)


Question: What will be printed on the form
after executing the following code:

Dim Blah As Integer


Print Blah
Blah = 10
Blah = 20
Print Blah
Blah = 30
Print "Blah"
Print Blah

After you've thinking about the answer, you can


check it by inserting the code above into a Command Button's
Click event, and press the button at run-time.

Anyway, the Answer can be found on the next page...

Working With Integers (Continue)


Answer:

0
20
Blah
30

Why is that?
Lets pass over the code line after line:

Dim Blah As Integer


A new Integer with the name Blah has been declared

Print Blah
Will print the Value that found in the Blah variable.
But there is nothing in the Blah variable!
The Blah variable has just been declared, and we
didn't put inside it any value yet.
The default value of any integer variable is 0.
When you write :
Dim Blah As Integer

25
It's like you've written:
Dim Blah As Integer
Blah = 0

So it will print the value that found right now


in the Blah variable - 0

Blah = 10
Now the Blah variable holds the number 10

Blah = 20
Now the Blah variable holds the number 20
What's happened to the 10 that was inside it?
It has been deleted!
A variable can holds only one value, and when
you put in it a value, the old value is being immediately deleted.

So what is the differents between

Blah = 20

and

Blah = 10
Blah = 20

There is no differents!
In both cases the Blah variable will hold the number 20

Print Blah
Will print the value that found right now
in the Blah variable - 20

Blah = 30
Now the Blah variable holds the number 30

Print "Blah"
Will print the Text that found between the quotes - Blah

Print Blah

26
Will print the value that found right now
in the Blah variable - 30

Working With Integers (Continue)


Question: What will be printed on the form
after executing the following code:

Dim Blah As Integer


Blah = 2
Print 2 + 3
Print "2 + 3"
Print Blah + 3
Print Blah
Blah = Blah + 1
Print Blah
Blah = Blah + Blah
Print Blah

Working With Integers (Continue)


Answer:

5
2+3
5
2
3
6

Why is that?
Lets pass over the code line after line:

Dim Blah As Integer


A new Integer with the name Blah has been declared

Blah = 2
Now Blah holds the value 2

Print 2 + 3
When you execute command (the Print command in the case)

27
on expression, Visual Basic will evaluate the expression first,
and then will execute the command on the evaluation result.

In this case we execute the command Print on the expression 2 + 3.


The expression will be evaluated: 2 + 3 = 5.
The evaluation result is 5, and then Visual Basic will
execute the command Print 5
So in other words, Print 2 + 3 is equivalent to Print 5
after executing the Command Print 5 , 5 is been printed on the form.

Print "2 + 3"


As I said before, Everything that found inside quotes is being
treated as a string. So the string 2 + 3 will be printed on the form.
Print 2 + 3 will print the value of the expression 2 + 3,
Print "2 + 3" will print the text string 2 + 3

Print Blah + 3
Now the expression is Blah + 3.
when a variable is found inside expression, it's being
replaced with its value.
In this case the value of the variable Blah is 2.
So the Blah in the expression is being replaced with 2.
After the replacement the new command is Print 2 + 3
As we saw earlier, after executing this command
the value 5 will be printed on the form.

Print Blah
Will replace the Blah with its value.
Because the Blah value is 2, After the replacement
the new command will be Print 2
After executing this command, the value 2
will be printed on the form.

Blah = Blah + 1
The line above simply says:
Put in the Blah variable, the value of the expression Blah + 1
The computer is first evaluate the expression Blah + 1
Blah is being replaced with its value: 2.
After the replacement the computer evaluates the expression 2 + 1.
The expression value is 3.

28
So now, after the "Blah + 1" expression evaluation,
the command is: Blah = 3
As you know by now, this command will
put the value 3 in the Blah variable.
Summary:
After executing the command Blah = Blah + 1,
the value 3 will be inserted into the Blah variable.

Print Blah
Will replace the Blah variable with its value: 3.
So the command that will be eventually executed is Print 3

Blah = Blah + Blah


Will Put in the Blah variable, the value of the expression Blah + Blah
The computer is first evaluate the expression Blah + Blah
Blah is being replaced with its value: 3.
After the replacement the computer evaluates the expression 3 + 3.
The expression value is 6.
So now, after the "Blah + Blah" expression evaluation,
the command is: Blah = 6
After executing the command Blah = 6,
the value 6 is being inserted into the Blah variable.

Print Blah
Will replace the Blah variable with its value: 6.
So the command that will be eventually executed is Print 6

More Complicated Expressions


You can use the following operators in expressions:

+ Plus
- Minus
* Multiply
/ Division
( Openning parenthesis
) Closing parenthesis
^ Power

For example, this is a valid expression:


(Blah + 5) * MySecondVariable - (4 + 10 / Blah)

29
The order of the operators are like in math:
First "(" and ")" , then "^", then "*" and "/", and at last "+" and "-"

For example:
2 + 3 * 4 is equal to 14
(2 + 3) * 4 is equal to 20

More Variable Types


What will be printed on the form after
executing the following code?

Dim ABC As Integer


ABC = 4.8
Print ABC

Answer:
The Integer variable can't store a number with fraction,
So the computer will round the 4.8 to 5, and will
Insert 5 to the ABC variable.
So the Command Print ABC will print 5 on the form.

So how can you store a number with fraction in a variable?


For this purpose you have other variable types that can
store round numbers like the Integer type, and in addition can
store numbers with fractions.

The Variable types list:

Byte - Can store only Integer numbers between 0 to 255

Integer - Can store only Integer numbers between -32,768 to 32,767

Long - Can store only Integer numbers between -2,147,483,648 to 2,147,483,647

Single - Can store Non-Integer (numbers with fractions) Numbers


between -3.402823E38 to -1.401298E-45 for negative values,
and 1.401298E-45 to 3.402823E38 for positive values.

Double - Can store Non-Integer Numbers between


-1.79769313486231E308 to -4.94065645841247E-324 for negative values,

30
and 4.94065645841247E-324 to 1.79769313486232E308 for positive values

Why would I use Byte variable that can store Integer numbers
between 0 to 255, while I can use Integer variable that can store
numbers between -32,768 to 32,767?

The Answer is: Because the Byte variable is taking less memory.

So if you have variable that will not store numbers


greater than 255 or less than 0, declare it as Byte variable
and save a little amount of memory.

If you need to store Non-Integer numbers in variable,


declare it as Single or as Double.

The Declaring command is very simple:

Dim Abc As Double


Dim Blah As Single
Dim Popeye As Byte

Working With Strings


String variables are meant to store Text.
When you assign a text to a String variable,
you must put the text inside quotes.

For example:

Dim Abc As String


Abc = "Good Morning"

Question: What will be printed on the


form after executing the following code?

Dim kuku As String


kuku = "Hello!!!"
Print "kuku"
Print kuku

Answer:

31
kuku
Hello!!!

Why is that? Lets pass over the code line after line:

Dim kuku As String


Will create a new String variable

kuku = "Hello!!!"
Now the kuku variable holds the text Hello!!!

Print "kuku"
Everything that found inside quotes is being treated as text String,
So it will print kuku on the form.
The computer Is NOT associate the text "kuku" with
the variable kuku, because of the quotes.

Print kuku
Will replace the kuku with its value (Hello!!!),
and after the replacement will execute the new command Print "Hello!!!"

Working With Strings (Continue)


You can join two Strings together using the "+" operator.
Example:

Dim gogo As String


Dim popo As String
gogo = "Hello"
popo = "world"
gogo = gogo + " !!! " + popo
Print gogo

The code below will print Hello !!! world on the form.
The expression gogo + " !!! " + popo is equal to
Hello + " !!! " + world and that's equal to "Hello !!! world"
So eventually, the command that will be executed is gogo = "Hello !!! world”

32
Scope of Variables
Insert two Command Buttons to your form (with
the names Command1 and Command2),
and Add the following code to your program:

Private Sub Command1_Click()


Dim gogo As Integer
gogo = 100
End Sub

Private Sub Command2_Click()


MsgBox gogo
End Sub

Run the program, and click on the Command1 button.


the code that found in the Command1_Click event will be executed.
The gogo variable will be declared, and it will store the value 10.

Now press on the Command2 button.


In result, the MsgBox gogo Line will be executed.
But instead of displaying the value of the gogo variable (100),
It shows nothing, like if the gogo variable hasn't been declared at all!

The reason for all of this, is the scope of the variable.


Every variable that been declared, "Exist" only in the
Sub or function that he was declared in.

What is Sub? (We will learn about functions later)


Sub is a Block of code that starts with Sub and
ends with End Sub
Every event is a sub, because it begins with Sub and
ends with End Sub

For Example:

Private Sub Command1_Click()


MsgBox "Hello"
End Sub

Every line of code that found between the Sub Command1_Click()


and the End Sub is belong to the sub Command1_Click()

So because we've declared the gogo variable in the


Commad1_Click event, it's declared only within the sub, and
it's not declared in the Command2_Click event.

33
So if you want that a specific variable will be "exist" in
your whole program, no matter from which sub you call it,
what can you do?
The Answer is in the next page...

Scope of Variables (Continue)


As you saw in the previous page,
If you declare variable in a sub, it exist only
within the sub.

To declare variable that will be exist in all subs,


you have to declare it in the "Declarations area" of your code.
Choose "(General)" From the components List in the code window (Figure 1).

Figure 1

Put the gogo declaration statement in the "Declarations area".


Simply write:

Dim gogo As Integer

And delete the old statement that found


in the Command1_Click event.

After you've done so, your code should look like this:

Dim gogo As Integer

Private Sub Command1_Click()


gogo = 100
End Sub

34
Private Sub Command2_Click()
MsgBox gogo
End Sub

Now the gogo variable is being declared in the Declarations area


of your code, and should be available from every part of your code.

Lets check it out:


Run the program.
The gogo variable is being declared immediately when the
program is being started.

Press the Command2 Button.


A message box with the number 0 is popping.
It is because the gogo variable has been declared, but
we didn't assign any value to it yet, so right now its value
is the default value - 0.

Press the Command1 Button.


The value 100 is being assigned to the gogo variable.

Press the Command2 Button - a message box


with the value 100 is popping.

Choosing A Valid Name For Variable


When declaring on variable, you choose its name.
For example:

Dim Tuti As Integer

The example above will set the variable


name to be "Tuti".
The names you choose for your variables don't have
to have any meaning, but still there are some limitations
about the names you can call your variables.

The Rules:

1)The only characters that can appear in the name are


letters, numbers and the character _ (the underscore character)
You can't use other characters like: ` ! @ # % ^ & * ( )
Therefore, the following names are NOT valid: AB!, BB$, tot#o

35
2)The Name Must begin with a letter: You can't
use the names: 2abc, 3, 2345, _aba

3)You can't use space in the variable's name.


Therefore, the following names are NOT valid: A B, hello world

4)You can't call your variable with a name that is a Visual Basic
Command or Function (these names are been called "saved names").
For example you can't use the name Print, because there is
command in Visual Basic that called Print (which we used pretty much
in this tutorial).
You can know easily if a name is a saved name by typing it anywhere
in your code. All the saved names are being painted with blue color.
Few examples for saved names: Print, Sub, End, MsgBox

Examples for valid names:


a, A, AaAaA, aBhguKJhUJYf, abc123, abc123abc123, hello_world123

There is much more to learn about variables, like constants,


booleans, arrays and more.
What you've learnt by now is necessary for continuing
with the next lessons.
More advanced variables subjects will appear
during the next lessons.

The Command Button's KeyPress, KeyDown and KeyUp Events


The events that will be mentioned in the following pages
are commonly used, and without learning about them
you really can't go anywhere in Visual Basic programming.

To try these examples, start a new project (as being


taught in Lesson 1).

Add 1 Command Button to your form. The Command


Button is called by default Command1.

Copy the following code to the code window (you


can copy and paste it using Ctrl + C for copying
and Ctrl + V for pasting):

36
Private Sub Command1_KeyDown(KeyCode As Integer, Shift As Integer)
Print "KeyDown"
End Sub

Private Sub Command1_KeyPress(KeyAscii As Integer)


Print "KeyPress"
End Sub

Private Sub Command1_KeyUp(KeyCode As Integer, Shift As Integer)


Print "KeyUp"
End Sub

When the Command Button's KeyDown event will be executed,


"KeyDown" will be printed on the form,
When the Command Button's KeyPress event will be executed,
"KeyPress" will be printed on the form, and when
the Command Button's KeyUp event will be executed,
"KeyUp" will be printed on the form.

Run the program, and click the button with the mouse.
Nothing has happened.
It's because the KeyDown, Key_Press, and KeyUp events are
being executed Only when you press a key on the keyboard.

Now press any key on the keyboard, hold it down for few seconds,
and then release it.
Your form will look like this:

Figure 1

37
Lets see:
The first event that been executed is the KeyDown event,
because "KeyDown" was the first text that been printed on the form.

The second event was KeyPress, and then again KeyDown.


After every KeyDown event that been executed, a KeyPress
event had been executed.

We learnt that when a key is being holded down, the


KeyDown and the KeyPress events are being executed in
this order over and over again, until the key is up again.

When you release the key, the KeyUp event is being executed once.

Learning about Parameters


Parameters are variables that being passed to a Sub.

Look at the first line of the Command Button's Click event:

Private Sub Command1_Click()

And at the first line of the Command Button's KeyPress event:

Private Sub Command1_KeyPress(KeyAscii As Integer)

The Click event's first line is ended with


empty parentheses () and the KeyPress event's first
line is ended with (KeyAscii As Integer)

38
What is the (KeyAscii As Integer) ?
It's a parameter that been passed to the KeyPress event.

This parameter is an Integer variable with the name KeyAscii.


Like if you've declared Dim KeyAscii As Integer

Why do we need this variable?


Because its value is very useful.

The KeyPress event is being executed when the user


press a key, and This variable holds the Ascii value of the
key that been pressed.
With This Ascii value you can know on which key
the user has pressed.

For example, the Ascii value of the "A" character is 65.


If the user has pressed the key "A" on the keyboard,
The KeyAscii parameter value will be 65.

Lets see an example.


Insert the following line to the Command1 KeyPress event:

Private Sub Command1_KeyPress(KeyAscii As Integer)


Print KeyAscii
End Sub

Run the program and press several keys.


You will see the Ascii value of every key you're pressing.

Notice that the KeyAscii values of "A" and "a" are differents.
Every characters has its own KeyAscii value,
and 2 characters that are the same letter, but have different case,
have different KeyAscii value.

More About Ascii


How can I know what is the Ascii value of a specific character?
Use the Asc command.
For example, the following line:

Print Asc("b")

39
Will print on the form the Ascii value of the character "b".

How can I know which character's Ascii value is 98?


Use the Chr command.
For example, the following line:

Print Chr(98)

Will print on the form the character that its Ascii value is 98.

Learning about Parameters (Continue)


Look at the first line of the Command Button's KeyDown Event:

Private Sub Command1_KeyDown(KeyCode As Integer, Shift As Integer)

As you can see, the KeyDown event gets two parameters:


The KeyCode parameter, and the Shift parameter, both are
Integer type.

Every Sub can get no parameters (like the Click event), can get
one parameter (like the KeyPress event) or can get more than
one parameter.

If a sub is getting more than one parameter, the parameters


have to be separated with commas.
For example:

Private Sub MySubName (Parameter1 As String, Parameter2 As Integer, Parameter3 As String)

Lets check out the KeyDown event's parameters.

The first is KeyCode, and it holds the KeyCode value


of the pressed key.
The KeyCode value is usually different from the Ascii Value.

The different between KeyCode and Ascii, is that


every character has Ascii value (for example G, @, |, =, and more)
but there are some keys that don't represent any character, for example:
Alt, F4, Ctrl, The left arrow key.

These keys don't have Ascii value, but they have KeyCode value.

40
For example, the KeyCode value of the Ctrl Key is 17.

Ascii represent characters, while KeyCode represent Keyboard's keys.


Because of that, the characters "a" and "A" have different Ascii value,
but they have the same KeyCode value, because the same key
is typing "a" and "A".

The second parameter is Shift, and its value helps you


to determine if the user has pressed the Shift, Ctrl or Alt keys.
The Shift holds the value 1 if the user has pressed the Shift key,
the value 2 if the user has pressed the Ctrl Key,
and the value 4 if the user has pressed the Alt Key.

If the user has pressed the Alt key and the Shift key together,
the Shift value will be 4 (for the Alt key) + 1 (for the Shift key) = 5

Examples:

If the user has pressed the "A" key,


The KeyCode parameter will hold the number 65, and
the Shift parameter will hold the value 0.

If the user has pressed Shift and "A" together,


The KeyCode parameter will hold the number 65, and
the Shift parameter will hold the value 1.

The KeyUp event's parameters are the same as the KeyDown event's parameters.

MouseMove, MouseDown and MouseUp Events


Lets check out the Command Button's MouseMove,
MouseDown and MouseUp events.

We will do that like we've done before,


by inserting different Print commands to every event.

Copy the following code to your program:

Private Sub Command1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As


Single)

41
Print "MouseDown"
End Sub

Private Sub Command1_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As


Single)
Print "MouseMove"
End Sub

Private Sub Command1_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As


Single)
Print "MouseUp"
End Sub

Run the program.


Move the mouse over the form - nothing is happening.
Move the mouse over the Button - The Button's MouseMove event
is being executed every time you move the mouse over it, therefore
you see that "MouseMove" is being printed on the form
every time you move your mouse over the button.

Click on one of the mouse buttons when the mouse is over the button,
and hold the button down.
The MouseDown event is being executed.
Release the button, and the MouseUp event is being executed.

MouseMove, MouseDown and MouseUp Events (Continue)


Lets check out these events parameters.

Private Sub Command1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As


Single)

Each one of these events gets the same parameters:


Button, Shift, X and Y.

The Shift parameter is the same as the KeyDown


event's Shift paramater.

For example, if you'll press the Shift button while clicking


the mouse, the Shift value will be 1.

The Button parameter value is 1 if you've clicked


the left mouse button, and 2 if you've clicked the

42
right one.

The X and Y parameters are the X and Y coordinates of


the mouse cursor, relative to the upper left button corner.
The coordinates of the upper left button corner are (0, 0)
The coordinates of the Bottom Right button corner are (Button Width, Button Height)

You can try a little example.


Put the following line in the Command Button's MouseMove event:

Print X, Y

This line will print the X coordinate, and next to it


the Y coordinates (For example, the line:
Print "Hello", "World"
will print: Hello World).

Additional Command Button's Properties


Add 1 Command Button to your form,
and change the following properties to
see what they do.

Caption - the text that appear on the button

Font - The Caption's font (Figure 2).

Figure 2

ToolTipText - Insert into this property the text


that will appear when the mouse is stand still
on the button (Figure 3).

Figure 3

43
Enabled - Setting this property to "False" will make
the button be gray, and the user will no be able to press on it (Figure 4).

Figure 4

BackColor - This is the background color of the button (Figure 5).


This property will take affect only after you will set the
Button's Style property to 1 - Graphical

Figure 5

44
Picture - The Picture that appear on the button (Figure 6).
This property and all the following Picture related properties will
take affect only after you will set the
Button's Style property to 1 - Graphical

Figure 6

DisabledPicture - The Picture that will appear on the button when


it disabled (When the Enabled property is "False", like in Figure 4).

DownPicture - The Picture that will appear on the button when


the button is being pressed.

Visible - If you will set this property to "False", the Button


will not appear on your form at run-time.

MousePointer - Choose here the mouse pointer (Arrow, Hourglass, and more)
when it will be over the button.
If you will set the property to be 99-Custom,
The mouse pointer will be the icon that you will select in the MouseIcon property.

Left - The Button X coordinate, relative to the form left border.

Top - The Button Y coordinate, relative to the form Top border.

Width - The Button width.

Height - The Button height.

Additional Form's Properties


The Form has many of the Command Button's properties
(MousePointer, BackColor, Visible and more).
He also has additional properties:

45
Caption - The text that appear in the Form's title bar,
and in the taskbar.

Icon - The Icon that appear in the form's title bar (Figure 7)
and in the Task bar (Figure 8).

Figure 7

Figure 8

ControlBox - Set this property to "False" to remove


the title bar's Close, Minimize and Maximize buttons (Figure 9).

Figure 9

MaxButton - Set this property to "False" to disable


The title bar Maximize Button.

MinButton - Set this property to "False" to disable

46
The title bar Minimize Button.

ShowInTaskbar - Setting this property to "False" will


cause the form not showing in the task bar.

WindowState - The initial appearance style of the form:


Minimized, Maximized, or normal.

The Form's KeyPreview Property


To understand this property,
lets look on the following example:

Start new project, and add 1 Command Button


(named Command1) to your form.
verify that the Form's KeyPreview property is set to "False".
Add the following code to your program:

Private Sub Command1_KeyPress(KeyAscii As Integer)


Print "Button Pressed"
End Sub

Private Sub Form_KeyPress(KeyAscii As Integer)


Print "Form Pressed"
End Sub

The code above will print "Button Pressed" on


the form when the Command Button's KeyPress event
will be executed, and print "Form Pressed" when the
Form's KeyPress event will be executed.

Run the program and press any key on the keyboard.


"Button Pressed" is appearing on the form, but
"Form Pressed" isn't appearing.

The Form's KeyPress event hasn't been executed.

When the KeyPreview property is "False",


if any control is found on the form (the command button in this case),
It will get all the Key events (KeyPress, KeyDown and KeyUp)
instead of the form.

47
To allow the Form's Key events be executed,
set the KeyPreview property to "True".

Lets try it. Set the KeyPreview


property to "True", run the program again
and press any key.
The Form's KeyPress event has been executed,
in addition to the Button's KeyPress event that
been executed too.

Notice That the form's KeyPress event executed


before the Button's event.

Setting Properties At Run-Time


By now you know how to set a component
property before running your program (=at "Design Time"),
Now we will learn how to do that during program's Run-Time.

To change a property, use the following syntax:

TheControlName.ThePropertyName = TheNewPropertyValue

For example, suppose we have Command Button


With the name "Command1", and we want to
set its Caption property to be "Hello".
To do that, we will use the following code:

Command1.Caption = "Hello"

To test it, simply copy the line above to your


Command1 Click event, run the program
and click the button at run-time.

Note that the Hello is inside quotes because


it's a String.
You can assign a variable value to a property:

Dim MyVar As String


MyVar = "Hello"
Command1.Caption = MyVar

This code will do exactly the same as the code line above it.
Note that MyVar is without quotes, because it's variable.

And how do you set a Form caption property at run-time?

48
exactly the same:

Form1.Caption = "Hello"

Setting Properties At Run-Time (Continue)


Not all the properties get text values.
For example, Visible property can be "True" or "False"

False and True are not text strings, but


Visual Basic commonly used values that called "Boolean"

Therefore, when you assign these values to property,


You don't have to use the quotes, For example:

Command1.Visible = False
Form1.Enabled = True

Some of the properties values has the following syntax:


Number - String

For example, the Command Button's Style property can


get 2 values:

0 - Standard
1 - Graphical

To set these properties value, omit the string.


For example:

Command1.Style = 1
Form1.WindowState = 2

Some properties represent graphics, for example


The Picture property.

To set these properties at run-time, use


the LoadPicture Command.
The example below will load the ICO file "d:\games\toto.ico"

49
to the Picture property of Command Button with the name "MyButton"

MyButton.Picture = LoadPicture("d:\games\toto.ico")

Setting the BackColor Property


You can set the BackColor property at run-time in 2 ways.

Way 1: Using the Color's numeric value


Every color has numeric value.
You can simply assign this value to the BackColor property.

For example, The numeric value of the red color is &H000000FF&


If you want to set the Form BackColor property to red,
use the following code:

Command1.BackColor = &H000000FF&

You can find what is the numeric value of every


color by making the following simple steps:

Click on the BackColor property arrow button


in the properties window (Figure 10).

Figure 10

Then click on the Palette Tab (Figure 11).

Figure 11

50
Select your desirable color (Figure 12).

Figure 12

The color value will be displayed in the BackColor Property cell (Figure 13).

Figure 13

And once again, if you setting a Command Button's color,


don't forget to set its Style property to 1 - Graphical.

To learn the second way, you'll have to learn

51
a little bit about Constants.
All of this in the next page...

etting the BackColor Property (Continue)

Way 2: Using the Colors Constants


First of all, what is Constant?
Constant is a variable that its value can not be changed.
Constant holds a common used value.
For example, the Constant vbRed holds the value
of the red color - &H000000FF&

Instead of writing in your code:

Command1.BackColor = &H000000FF&

You can write:

Command1.BackColor = vbRed

The 2 statements above are identical, because


vbRed = &H000000FF&

Where are these constants came from?


Visual Basic automatic declare them
when the program starts.

Imagine it like as the following code is


automatic being entered to your program:

Dim vbRed As Long


vbRed = &H000000FF&

Dim vbBlue As Long


vbBlue = &H00FF0000&

And so on...

But with one exception: You can't


change the constants value.

52
For example, the following code is NOT allowed:

vbBlue = 5

There are more Color constants, a partial list:

vbRed, vbBlue, vbBlack, vbGreen, vbWhite, vbYellow

You can declare your own constants.


The constant declaration syntax:

Const MyVariableName = MyVariableValue

For example, the following code will declare a const


variable with the name Piano and the (const) value "abcdef"

Const Piano = "abcdef"

After this declaration, the Print Piano


code line will print abcde on the form.

In addition, the following code line will not be allowed:

Piano = "gggg"

Because it's been declared as a Const,


and Const value can not be changed.

What Are Conditional Statements?


Suppose you want to protect your program with password.
You ask from the user to enter the password.
If the password is correct - you want to let the user in, if not - you want to end the program.

53
To do this, you have to use conditional statement because
the code you will execute (let the user in or end the program) is
depend on what is the password that the user has entered.

One of the basics of Conditional statement are Boolean variables.


Boolean variables are commonly used in programming,
and you have to understand them before continuing with conditional statements.

Boolean Variables
As we learnt, String variables store text, and
Integer Variables Store numbers.
Boolean variable stores one of the following constant values:
"True", or "False".

For example:

Dim Kuku As Boolean


Kuku = True
Dim YoYo As Boolean
YoYo = False

What are the True and False stand for?


They are the result of every "Boolean expression".

Boolean Expressions
Boolean expression is like a question that
the answer to it is "True" or "False"

For example:
Is 4 Plus 6 is 10? True
Is 2 bigger than 4? False

But the question


How much is 4 Plus 6?
Is not a boolean expression, because its answer
is 10 (and not True or False)

Examples of Boolean expressions in the next page.

Examples Of Boolean Expressions


The following code:

54
Dim ABC As Boolean
ABC = (3 > 4)
Print ABC

Will print "False" on the form.


The value of the boolean expression 3 > 4
is "False", because 3 is not greater than 4.

The following code:

Dim ABC As Boolean


ABC = ("abf" = "abf")
Print ABC

Will print "True" on the form.


The value of the boolean expression "abf" = "abf"
is "True", because "abf" is equal to "abf"

The following code:

Dim ABC As Boolean


Dim A As Integer
Dim B As Integer
A=1
B=2
ABC = (A + 1 = B)
Print ABC

Will print "True" on the form,


because the value of the boolean expression (A + 1 = B) is "True".

In Boolean expressions you can use the following signs:

= Equal to
<> Not Equal to
> Greater than
< Smaller than
>= Greater than or Equal to
<= Smaller than or Equal to

55
InputBox
In the next examples we want to receive a value
from the user when the program is running.
To do so we will use the InputBox command.

The InputBox command syntax is:

VariableName = InputBox ("Text to Display")

After executing this command, the variable


will get the value that the user has entered.

Example:
Put 1 Command button on your form and
enter the following code to its click event:

Dim Elvis As String


Elvis = InputBox("Please Enter your name")
Print Elvis

Run the program and click the button.

A Message Box is appearing with the


text "Please Enter your name" (Figure 1).

Figure 1

Type your name in the text box, and press OK.


Your name will be printed on the form.

Conditional Statements
The syntax of the conditional statement:

56
If (boolean expression) Then
The code to execute if the boolean expression is equal to True
Else
The code to execute if the boolean expression is equal to False
End If

Lets make a password protected program.


We want to prompt the user to enter the password
at the very start of the program, so put the following
code in the Form_Load event:

Dim Password As String


Password = InputBox("Please enter the password")
If (Password = "let me in") Then
MsgBox "The Password is correct!"
Else
MsgBox "Incorrect Password!"
End If

Run the program.


An InputBox is appearing.
Type "let me in" (without the quotes) in the InputBox.
Note that the text is case sensitive, and if you will
type "LET ME IN" you will get a message box with the
text "Incorrect Password!".

Lets understand how this code works:

The boolean expression (Password = "let me in") value is True


ONLY if the Password variable value is "let me in".

If this boolean expression's value is True, the code


that will be executed is the code that located between
the Then and the Else (MsgBox "The Password is correct!")

57
If this boolean expression's value is False, and this
happens when the Password variable value is NOT "let me in",
the code that will be executed is the code that located between
the Else and the End If (MsgBox "Incorrect Password!")

If you enter a wrong password, a message box is appearing,


but the program is continue running.
To end the program, use the command End .
This command is simply shut down the program.

Put the End command in the "Else Section":

Dim Password As String


Password = InputBox("Please enter the password")
If (Password = "let me in") Then
MsgBox "The Password is correct!"
Else
MsgBox "Incorrect Password!"
End
End If

Using "And" and "Or" In Boolean Expressions


We can use "And" and "Or" operators to make more
complicated boolean expression.

In the last example we used the boolean


expression Password = "let me in".

This boolean expression is "True" if


the Password is "let me in", and "False"
If the Password is not.

How can we make a boolean expression


that will be "True" if the Password is
"let me in" or "sam sent me", and if the
Password is other than the two above, the
boolean expression will be "False"?

To create this boolean expression we will use the "Or" operator:

(Password = "let me in") Or (Password = "sam sent me")

58
Put the following code in your Form_Load event:

Dim Password As String


Password = InputBox("Please enter the password")
If (Password = "let me in") Or (Password = "sam sent me") Then
MsgBox "The Password is correct!"
Else
MsgBox "Incorrect Password!"
End
End If

Run the program.


If you'll type "let me in" or if you'll type "sam sent me"
the password will be correct.
If you'll type any other text the program will shut down.

The "Or" is operator, the same as "+" is operator.


How the "+" operator works we already know:
5 + 6 = 11
But how the "Or" Operator works?

The "+" operator is being executed on numbers:


Number + Other Number = The sum of both numbers.

The "Or" operator is being executed on "True" or "False":


False Or True = True
True Or False = True
True Or True = True
False Or False = False

The 4 examples above are the only options


of using the "Or" operator.

Lets see what effect has the "Or" operator on


the boolean expression we used:

(Password = "let me in") Or (Password = "sam sent me")

First, the left and right boolean expressions


are being evaluated (Figure 2).

For example, if the Password is "let me in" then


(Password = "let me in") is True

59
and (Password = "sam sent me") is False.

Then the boolean expression is look like this:


(True) Or (False)

As we saw in the 4 examples above, True Or False = True


So the final result of the expression is True (Figure 2).

Figure 2

(Password = "let me in") Or (Password = "sam sent me")

True Or False

True

This boolean expression will be True if


the password is "let me in" because True Or False = True,
the expression will be True if the password is "sam sent me"
because False Or True = True,
the expression will be False if the password is NOT "let me in"
and NOT "sam sent me" because False Or False = False.

Using "And" and "Or" In Boolean Expressions (Continue)


The "And" operator is similar to the "Or"
operator, except it has different Effects on boolean expressions:

True And True = True


True And False = False
False And True = False
False And False = False

When using the "And" operator, the


expression will be True only if both
boolean expressions are True.

For example, copy the following code


to your Form_Load event:

Dim UserName As String


Dim Password As String

60
UserName = InputBox("Please enter the user name")
Password = InputBox("Please enter the password")
If (Password = "let me in") And (UserName = "elvis") Then
MsgBox "The login is correct!"
Else
MsgBox "Incorrect Login!"
End
End If

This code will pop up two InputBoxes.


The first will ask you to enter the user name,
and the second will ask you to enter the password.
The login will be correct only if both user name
and password are correct.

The boolean expression (Password = "let me in") And (UserName = "elvis")


is True only if (Password = "let me in") is True, and
(UserName = "elvis") is True, because
True And True = True, and any other
combination is equal to False.

Using The "Not" Operator


The "Not" operator has very simple function:

Not True = False


Not False = True

Before we continue,
I'll mention that you don't have to include
"Else" in the "If" statement.

For example:

Dim Password As String


Password = InputBox("Please enter the password")
If (Password = "let me in") Then
MsgBox "The Password is correct!"
End If

If the password is correct, The code above


will display a message box with the text
"The Password is correct!".
Otherwise, the code will do nothing,

61
because there is no "Else".

Lets see an example of using the operator "Not".


Copy the following code to your Form_Load event:

Dim Password As String


Password = InputBox("Please enter the password")
If Not (Password = "let me in") Then
MsgBox "Incorrect Password!"
End
End If

The boolean expression: Not (Password = "let me in")


is True only if the Password is not "let me in". Why?
If the Password is not "let me in",
(Password = "let me in") is False (Figure 3) ,
and we get the boolean expression: Not (False).
Not False = True, so eventually, the
expression value is True (Figure 3).

Figure 3

Not (Password = "let me in")

Not False

True

In conclusion,
The code above will display a message box
with the text "Incorrect Password!" ONLY if
the password is different from "let me in"

More Advanced Boolean Expressions


You can combine the operators "Not", "And" and "Or" in
the same boolean expression, using the parentheses "(" and ")"

For example:

(True And False) Or (Not False) = True

62
Figure 5

(True And False) Or (Not False)

False Or True

True

The priority of the "Not" operator is higher than


the priority of "And" and "Or" operators.

For example:

Not True And False = False, because


The first operater to be executed is the "Not" (Figure 6):
Not True = False.
Then we get the following boolean expression:
False And False = False.

Figure 6

Not True And False

False And False

False

If we will executed the "And" operator before


the "Not" operator, we would get WRONG answer (Figure 7).

Figure 7

Not True And False

Not False

63
True

A Teaser:
What will be printed on the form after
executing the following code?

Dim Elvis As Boolean


Elvis = (Not False And True) And Not ((True And Not False) Or False)
Print Elvis

Answer:

Nested Conditional Statements


Untill now, we could program simple conditional statements:
If the password is xxx - do something,
and if not - do other thing.

But what if we want to write more complicated conditional statements:


If the password is xxx - do something,
If the password is yyy - do something else,
If the password is zzz - do something else,
and if the password is none of the above - do something else.

To do that we'll use "ElseIf":

64
Dim Number As Integer
Number = InputBox("Please enter your age")
If (Number > 50) Then
MsgBox "you are older than 50"
ElseIf (Number < 20) Then
MsgBox "you are younger than 20"
Else
MsgBox "your age is between 20 and 50"
End If

How does that code above work:

First, the first boolean expression is being evaluated:


(Number > 50)
If it's equal to True then the line that following it
(MsgBox "you are older than 50") will be executed, and
the "If statement" will be ended here, so the next
boolean expression (Number < 20) will not be checked.
If it's equal to False, the next boolean expression will be checked:
(Number < 20)
If it's equal to True, the line that following it
(MsgBox "you are younger than 20") will be executed, and
the "If statement" will be ended here.
If it's equal To False, the "Else Statement" will be executed:
MsgBox "your age is between 20 and 50"

Only 1 of the lines will be executed!

You can use more than one "ElseIf" in your "If Statement",
For example:

Dim Name As String


Name = InputBox("Please enter your name")
If (Name = "elvis") Then
MsgBox "your name is elvis"
ElseIf (Name = "tim") Then
MsgBox "your name is tim"

65
ElseIf (Name = "john") Then
MsgBox "your name is john"
ElseIf (Name = "steve") Then
MsgBox "your name is steve"
Else
MsgBox "I don't know you"
End If

Using "Select Case"


The "Select Case" conditional statement
is very useful when you have in your conditional
statement many conditions.

For example, in the last page we had the following code:

Dim Name As String


Name = InputBox("Please enter your name")
If (Name = "elvis") Then
MsgBox "your name is elvis"
ElseIf (Name = "tim") Then
MsgBox "your name is tim"
ElseIf (Name = "john") Then
MsgBox "your name is john"
ElseIf (Name = "steve") Then
MsgBox "your name is steve"
Else
MsgBox "I don't know you"
End If

When you have many conditions, the "If Statement"


become too bulky.
In this case, you can use instead of it the "Select Case Statement".
The following "Select Case Statement" is do EXACTLY the same
thing as the code above:

Dim Name As String


Name = InputBox("Please enter your name")
Select Case Name
Case "elvis": MsgBox "your name is elvis"
Case "tim": MsgBox "your name is tim"
Case "john": MsgBox "your name is john"
Case "steve": MsgBox "your name is steve"
Case Else: MsgBox "I don't know you"
End Select

66
The "Select Case" syntax is very simple:

It Begins with:
Select Case VariableName

Then comes the conditions.


Every condition has "Case" before it, and ":" after it.
The "Select Case" conditions are little different from the "If" conditions:

The Select Case Condition The equivalent "If" Condition


Case "elvis" VariableName = "elvis"
Case Is <> "elvis" VariableName <> "elvis"
Case 5 VariableName = 5
Case Is <> 5 VariableName <> 5
Case Is > 5 VariableName > 5
Case Is >= 5 VariableName >= 5
Case Is < 5 VariableName < 5
Case Is <= 5 VariableName <= 5

After every condition, comes the line that will be executed


if the condition will be "True".

For example, the line:

Case "elvis": MsgBox "your name is elvis"

Is the same as:

If (VariableName = "elvis") Then


MsgBox "your name is elvis"
End If

After all conditions, comes the Else condition (It's


optional condition, and you can omit it if you want):
Case Else:

67
This condition will be executed ONLY if none
of the conditions above was executed.

After all of the conditions, the statement closed with End Select

Note that you can have more than 1 line to executed


in each condition. For example:

Dim Name As String


Name = InputBox("Please enter your name")
Select Case Name
Case "elvis": MsgBox "your name is elvis"
MsgBox "you are the king!"
MsgBox "I didn't know you are alive!"
Case "tim": MsgBox "your name is tim"
Case "john": MsgBox "your name is john"
Case Else: MsgBox "I don't know you"
End Select

68

You might also like