Monday, June 22, 2009

Visual Basic Notes

Introduction To Visual Basic
Visual Basic:
Visual Basic is a tool that allows you to develop windows (Graphical User Interface-GUI) applications. Visual Basic is event-driven language, which means that the code remains idle unless called upon to respond to some event (button pressing, menu selection, mouse clicking,………….). When an event is detected, the code corresponding to that event is executed.
Features of Visual Basic (VB):
Visual Basic provides the following powerful features.
o Full of objects-----you draw on the application form
o Response to mouse and keyboard actions
o Lots of icons and pictures for your use in application.
o Clip board and printer access
o Full Array of mathematical, String handling, and graphics functions
o Can handle fixed and dynamic variable and control arrays
o Sequential and random access file support
o ActiveX support
o Powerful database access tools
o Useful debugger and error-handling facilities
VB ENVIRONMENT
IDE (Integrated Development Environment)
The Visual Basic IDE is a complete application development environment. The IDE allows you to design, develop and edit an application, debug it for possible errors and the run it to see the output. All these facilities are available in the VB IDE.
The VB IDE consists of the following commonly used components or tools.
1. Title Bar
2. Menu Bar
3. Tool Bar
4. Form Window
5. Toolbox
6. Properties Window
7. Form Layout Window
8. Project Explorer Window
9. Immediate window
Now we explain these components briefly.
1. Title Bar:
The title bar indicates the project name, the current Visual Basic operating mode, and the current form. The title bar appears at the top most of VB IDE.
ii) Menu Bar:
The menu bar has drop-down menus from which you control the operation of the Visual Basic environment. The menu bar consists of menus like File, Edit, View, Project, Debug, and Run etc.
iii) Tool Bar:
The tool bar has buttons that provide shortcuts to some of the menu options like Add Project, New Form, and Save project etc.
iv) Form Window:
The Form Window is the central point to developing Visual Basic applications. It is the place where you draw you application.
v) Tool Box:
The Tool Box is the selection menu for controls used in your application. The Tool Box contains a set of controls like label, command buttons, text boxes, list boxes, option buttons and so on.
vi) Properties Window:
The Properties Window is a set of properties or characteristics that will be assigned to various control objects during designing. These properties include control object name, appearance, back color, caption, size of control and so on.
vii) Form Layout Window:
The Form Layout Window shows where your application form will be displayed relative to your monitor’s screen when the program is executed.
viii) Project Window:
The project window displays a list of all forms and modules. These forms and modules make a Visual Basic application. The project window also contains a view of the form or code windows containing the actual basic coding.
ix) Immediate Window:
The Immediate Window is a small output window. The immediate window allows you to check simple calculations easily and immediately.
You can enable it by using the short cut key Ctrl+G. The immediate window is for testing simple calculations like print 2+3, the immediate window will display the output is 5.
BASIC CONTROLS
Some of the Visual Basic controls are:
1. Check Boxes
2. Option Buttons
3. Frames
4. Command Buttons
5. Labels
6. Text Boxes
7. List Boxes
8. Combo Boxes
9. Picture Boxes
10. Drive List Boxes
11. Directory List Box
12. File List Box
Now we explain them one by one as follow
i) Check Boxes:
Check Boxes provide a way to make choices from a list of values. Some, all, or none of the choices in a group may be selected.
Check Box Properties:
The following are the properties of Check Box
Caption………. Identifying text next to box
Font. …………Sets font type, style, size
Values…………Indicates if Unchecked (0, Vbunchecked),
Checked (1, Vbchecked)
Check Box Events:
Click………Triggered when a box is clicked. Value property is automatically changed by Visual Basic
Option Buttons

Option Buttons provide the capability to make a single choice from a list of values. Hence option buttons work as a group, only one of which can a have a True (or selected) value.
Option Buttons Properties:
The following are the properties of Check Box
Caption………. Identifying text next to button
Font. …………Sets font type, style, size
Values…………Indicates if selected (True),or not (False) One button in a group of
option buttons should always be initialized to True at design time.
Option Buttons Box Events:
Click………Triggered when a button is clicked. Value property is automatically changed by
Visual Basic.
Frames + Command Buttons
Frames provide a way of grouping related controls on a form. To group controls in a frame, you first draw the frame. Then the associated controls must be drawn in the frame. This allows you to move the frame and controls together. And once a control is drawn within a frame, it can be copied and pasted to create a control array within the frame.
FRAME PROPERTIES:
Caption………. Title information at the top of frame
Font. …………Sets font type, style, size
iv- Command Buttons: Command Button is the most widely used control of the Control box.
Command Button Properties:
The following are the properties of Command button
Appearance……Selects 3-D or flat appearance
Caption………. text to be displayed on button
Font. …………Sets font type, style, size
Command Button Events:
Click………Triggered when button is clicked.
Label Box + Text Box
v- Label Boxes:
A label box is a control that you use to display a text that user can’t enter directly.
Label Properties:
The following are the properties of Label box.
Alignment……… Aligns caption within the border.
Appearance……Selects 3-D or flat appearance
Caption………. text to be displayed on button
Font. …………Sets font type, style, size
Label box Events:
Click………Triggered when label is clicked.
Dbclick…..Triggered when label is double-clicked.
vi- Text Box:
A Text Box is used to display information entered at design time, by a user at run time, or assigned within code. The displayed text may be edited.
Text Box Properties:
The following are the properties of text box.
Appearance……Selects 3-D or flat appearance
Caption………. text to be displayed on button
Font. …………Sets font type, style, size
Border Style……Determines type of border.
MultiLine……..Specifies whether text box displays single
line or multiple lines.
Text box Events:
Change………Triggered every time the text box property changes.
KeyPress…..Triggered when a key is pressed.
List Box + Combo Box
List Boxes:
A List Box displays a list of items from which the user can select one or more items.
List Box Properties:
The following are the properties of list box.
Appearance……Selects 3-D or flat appearance
List………. Array of items in list box.
Sorted.……True means items are selected, otherwise
items appear as added.
ListCount…. Number of items in list.
Text……….Text of most recently selected items.
List box Events:
Click……Triggered when an item in list is clicked.
Dbclick…Triggered when an item in list is double- clicked.
vii- Combo Box:
The combo box is similar to the list box. The differences are a combo box includes a textbox on top of a list box and only allows selection of one item.
Combo Box Properties:
The following are the properties of Combo box.
Appearance……Selects 3-D or flat appearance
List………. Array of items in list box portion.
Sorted.……True means items are selected, otherwise
items appear as added.
ListCount…. Number of items in list.
Text……….Text of most recently selected items.
Combo box Events:
Click……Triggered when an item in list is clicked.
Dbclick…Triggered when an item in list is double- clicked.
Picture Boxes
The picture box allows you to place graphics information on a form.
It is best suited for dynamic environments. For example, when doing animation.
Picture box Properties:
The following are the properties of Picture box.
AutoSize……if True, box adjusts its size to fit the displayed graphic.
Font……. Sets the font size, style, and size of picture.
Picture….. Sets the graphics file to display in the picture box.
Picture box Events:
Click……Triggered when a picture box is clicked.
Dbclick…Triggered when a picture box is double-clicked.
Drive List Box + Directory List Box
The Drive List Box control allows a user to select a valid disk drive at run- time. It displays the available drives in a drop-down combo box. No code is needed to load a drive list box.
Drive List Properties:
Drive……..Contains the name of the currently selected drive.
Drive List Events:
Change……Triggered when the user/program changes the drive selection.
xi- Directory List Box:
The Directory List Box control displays an ordered, hierarchical list of user’s disk directories and sub directories.
Directory List Box Properties:
Path……..Contains the current directory path.
Directory List Box Events:
Change……Triggered when the directory selection is changed.
xii- File List Box:
The File List Box control locates and lists files in the directory specified by its path property at run-time.
File List Box Properties:
FileName……..Contains the currently selected file name.
Path……….Contains the current directory path.
File List Box Events:
Dbclick…Triggered when an item in list is double-clicked.
Basic Concepts of Visual Basic
Variables
Variables are used by Visual Basic to hold information needed by an application. A variable has to be declared before using it in an application.
General syntax for declaring a variable is as follow
Dim variblename As datatype
Where variablename is any valid name of variable, and datatype show the type of the data that will be stored in the variblename.
Variable Declaration
There are 3 ways for a variable to be declared.
1. Default.
2. Implicit
3. Explicit
i. Default Declaration
If variables are not implicitly or explicitly declared. They are assigned the variant type of default. The variant data type is a special type used by VB that may contain numeric, string or double/float data.
A variable can be declared using the default declaration as
Dim Var1, Var2
Var1=”Ali”
Var2=300
Here Var1 & Var2 are the variables of type varient. Var1 holds the string data
“Ali” & Var2 holds the numeric data 300.
Note that in the default declaration the As datatype part is optional, the datatype is the variant by default.
ii. Implicit declaration
To implicitly declare a variable, use the corresponding suffix. For example
Name$=”Ali Khan” creates a sting variable
While
Marks%=300 creates a Integer variable
Different variblenames have different suffix for datatypes as shown in the following table.
Data Type Suffix Example
String $ Name$=”Ali”
Integer % Marks%= 300
Long & Distance&=654
String (Floating) ! Age!=20.5
Double # Average# = 345.67435
Currency @ Price@ =$20
Date None Dob=01-03-1976
Object None Mybutton = Picture
Name None Var1=500
iii. Explicit Declaration
The general syntax for explicit declaration is as follow
Dim Variable as Data type
e.g. Dim myname As String
Dim Marks As Integer
Dim Average As Double
Now assigning values to these variables, we have
myname = “Ali”
Marks= “300”
Average= 35.667
Rules for naming variables
The following are the rules for naming variables.
o A variable name must begin with letter.
o A variable name must not exceed 40 characters.
o A variable name must be unique in its scope.
o Reserved words are not allowed.
o No blank spaces are allowed in variable name.
Types of Variables
There are six main types of variables.
1. Numeric
2. String
3. Boolean
4. Date
5. Variant
6. Object.
Now we explain them one by one briefly as follow.
1. Numeric
Numeric variables are used to store numbers in Visual Basic. Numeric data types include:
1. Integer Variable
It can be declared as follow
Dim SNo As Integer.
1. Long Integer
It can be declared as follow
Dim Distance as Long
1. Double Variable
It can be declared as follow
Dim area as double
1. Currency Variable
It can be declared as follow

Dim Price As currency
1. String
String Variables are used to store the string/text data e.g. a studentname or address
It can be declared as follow
Dim myname As String

1. Boolean
The Boolean variable store either true or false value. It can be declared as follow
Dim Check as Boolean
To initialize the check
Check = True or Check = 5
Both hold true values in Check.
1. Date
The date variables are used to store both date and time. It can be declared as follow
Dime DOB as Date
To initialize it, we have
e.g DOB = “01-02-2000”
DOB = “3:30:30 am”
v. Variant
The variant variable is the most flexible data type of Visual Basic variables,
because it can accommodate other date types. A variant variable can be
declared as
Dim Var1 as Variant
Dim Var 2 as Variant
Var1 = “Ali”
Var2 = 300
If variant variable holds string value, Visual Basic treats it as string.
If variant variable holds Inter value VB treats it as Integer.
Note: It is important to note that when a variable is used without declaring it, then the default type of that variable will be variant.
e.g. Dim Var1
Dim Var2
Var1 = “Ali”
Var2 = 300
The Var1 & Var2 are now considered by default as variant (as above)
vi.Object:
An object type variable refers to any one of Visual Basic object controls in tool box. An Object variable can be declared as
Dim Var1 as command Button
To initialize it
Set Var1=Command1
Now the following have the same purpose
Command1.caption = “Save”
Or Var1.caption.”Save”
Scope(Visibility) And Life Time Of Variables
To explicitly declare a variable, you first determine its scope. There are four levels of scope.
1. Procedure Level
2. Procedure Level, Static
3. Form and module Level
4. Global Level
Now we explain each one of them briefly.
1. PROCEDURE LEVEL:
Within a procedure, variables are declared with the Dim statement as
Dim mysno As Integer
Dim myname As String
Dim myage As Double
Procedure level variables declared in this manner do not retain their values once a procedure terminates. So the scope and lifetime of a procedure level variable is limited to the lifetime of a procedure.
II) PROCEDURE LEVEL, STATIC:
To make a procedure level variable retains its value upon exiting the procedure, replace the Dim keyword with Static as follow
Static mysno As Integer
Static myname As String
Static myage As Double
III)FORM AND MODULE LEVEL
Form level variables retain their values and are available to all the procedures within that form(module). Form level variables are declared in the declaration part of the general object in the form’s(module’s) code window. The Dim keyword is used as follow
Dim mysno As Integer
Dim myname As String
Dim myage As Double
IV) GLOBAL LEVEL:
Global variables retain their values and are available to all the procedures within an application. Module level variables are declared in the declaration part of the general object of a module’s code window. The Global keyword is used as follow
Global mysno As Integer
Global myname As String
Global myage As Double
EXAMPLE OF VARIABLE SCOPE:
Module1

Procedure Routine 1 has access to X, Y and A (does not retain values upon termination)
Procedure Routine 2 has access to X, Y and B (retains values)
Procedure Routine 3 has access to X, Z and A (does not retain values upon termination)
Operators
Operators are the words or symbols, which cause a program to perform some action on data.
Types of Operators
Visual Basic supports the following three types of operators.
1. Arithmetic operators
2. Relational operators
3. Logical operators
Now we explain them one by one briefly.
1. Arithmetic operators.
Visual Basic supports the following arithmetic operators.
Operators Purpose

+ To add numbers
_ To subtract numbers
* To multiply numbers
/ To divide numbers (Real)
\ To divide numbers (integer)
^ To find exponentiation of numbers
Mod To find the remainder of numbers when divided Program Example1: Using the + operator
Option Explicit
Dim Number1 As Integer
Dim Number2 As Integer
Dim Result As Integer

Sub form1_activate( )
Number1=10
Number2=4
Result=Number1+ Number2
Print Result
End Sub
OUTPUT: 14
Program Example2: Using the - operator
Option Explicit
Dim Number1 As Integer
Dim Number2 As Integer
Dim Result As Integer
Sub form1_activate( )
Number1=10
Number2=4
Result=Number1- Number2
Print Result
End Sub
OUTPUT: 6
Program Example3: Using the * operator

Option Explicit

Dim Number1 As Integer
Dim Number2 As Integer
Dim Result As Integer

Sub form1_activate( )
Number1=10
Number2=4
Result=Number1* Number2
Print Result

End Sub
OUTPUT:40
Program Example4: Using the / operator (Real Division)
Option Explicit

Dim Number1 As Integer
Dim Number2 As Integer
Dim Result As Integer

Sub form1_activate( )
Number1=10
Number2=4
Result=Number1/ Number2
Print Result

End Sub
OUTPUT: 2.5
Program Example5: using the \ operator (Integer Division)

Option Explicit

Dim Number1 As Integer
Dim Number2 As Integer
Dim Result As Integer

Sub form1_activate( )
Number1=10
Number2=4
Result=Number1\ Number2
Print Result
End Sub
OUTPUT: 2
Program Example6: Using the ^ operator
Option Explicit
Dim Number1 As Integer
Dim Number2 As Integer
Dim Result As Integer

Sub form1_activate( )
Number1=2
Number2=3
Result=Number1^ Number2
Print Result
End Sub
OUTPUT:( 2 ) 3= 8
Program Example7: Using the Mod operator

Option Explicit

Dim Number1 As Integer
Dim Number2 As Integer
Dim Result As Integer

Sub form1_activate( )
Number1=5
Number2=3
Result=Number1 Mod Number2
Print Result
End Sub
OUTPUT: 2 (Remaider, when divieded 5 by 3)
OR
A single Visual Basic Program that uses all the above Arithmetic
Operators.
Program Example: Using the +,-,*,/, \,^, and Mod operators

Option Explicit

Dim Number1 As Integer
Dim Number2 As Integer
Dim Add As Integer
Dim Sub As Integer
Dim Mul As Integer
Dim Div1 As double
Dim Div2 As Integer
Dim Exp As Integer
Dim Rem As Integer

Sub form1_activate( )
Number1=5
Number2=2
Add=Number1+ Number2
Sub= Number1- Number2
Mul= Number1* Number2
Div1= Number1/ Number2
Div2= Number1\ Number2
Exp= Number1^ Number2
Rem= Number1 Mod Number2

Print Add
Print Sub
Print Mul
Print Div1
Print Div2
Print Exp
Print Rem
End Sub
OUTPUT: 7
OUTPUT: 3
OUTPUT: 10
OUTPUT: 2.5
OUTPUT: 2
OUTPUT: 25
OUTPUT: 1
OR
A VB program that contains a Form and three text boxes and one command button Add, when the Add button is clicked the numbers in the two text boxes is added and the result displays in the third text box Result.
We write the following code in the click event of command button Add for the above program.
Sub command1_Click( )
Text3.Text= Val (Text1.Text) +Val (Text2.Text)
End Sub
OR
Write the above program using variables in the option explicit
Option Explicit

Dim Number1 As Integer
Dim Number2 As Integer
Dim Add As Integer
Dim Sub As Integer
Dim Mul As Integer
Dim Div1 As double
Dim Div2 As Integer
Dim Exp As Integer
Dim Rem As Integer

Sub form1_activate( )
Number1=Val ( Text1.Text)
Number2=Val (Text2.Text)
Add=Number1+ Number2
Sub= Number1- Number2
Mul= Number1* Number2
Div1= Number1/ Number2
Div2= Number1\ Number2
Exp= Number1^ Number2
Rem= Number1 Mod Number2

Print Add
Print Sub
Print Mul
Print Div1
Print Div2
Print Exp
Print Rem
End Sub
2- Relational Operators/ Comparison Operators
Visual Basic supports six comparison operators.
Operator Purpose
< Less than
> Greater than
< = Less than or Equal to
> = Greater than or Equal to
= Equal to
< > Not Equal to
3- Logical Operators
There are three logical operators used by Visual Basic.
They are as follow
Operator Purpose

AND The expression with AND operator returns
True value if operators on both sides of AND operator are true otherwise return false.

OR The expression with OR operator returns
True value if at least one operator on both sides of OR operator is true otherwise return false.

NOT The NOT operator is used for negation purpose.
COMMENTS (REMARKS)
Remarks are used to make a program more readable and understandable.
The remarks are ignored by compiler and interpreter.

HOW TO ADD REMARKS:
If you place ‘ (single quote) at the start of a line or Rem keyword at the start of a Visual Basic statement, then the statement will become a remark and will ignored by the compiler.
For Example:
This is a simple program to test remarks.
Rem This is a simple program to test remarks.
The above both the two lines are equivalent and represent remarks.
Concatenation of Strings:
For concatenation of strings Visual Basic use the & symbol or + symbol.
For Example: Suppose we have two strings s1, s2 to be concatenated
and assigned to a third string s3.
S1=”Hello”
S2=”Boys”
S3=S1+S2
Now s3 will have the value ”Hello Boys”
SELECTION STRUCTURE STATEMENTS
Decision making statements of Visual Basic consists of the following:
1. If-Then
2. If-Then-Else
3. Select statement
Now we explain them one by one as follow
1. If –Then:
If-Then statement is used to perform an action if the condition is true, otherwise it skips the action.
General Synatx:
If condition Then statement End if
OR If condition Then
Statement
End if
Program Example1:
Start Visual Basic with standard, Exe file, Place a command button on the form, and write the following code in click event.
Dim I As Integer
Dim J As Integer
I=20
J=10
If (I>J) Then
Print “Large Number is=”,I
End if
OUTPUT: Large Number is=20
Program Example2: Now we modify the above program.
Suppose now the if condition is false, so the it will display nothing.
Dim I As Integer
Dim J As Integer
I=10
J=20
If (I>J) Then
Print “Large Number is=”,I
End if
OUTPUT: (No output as the test condition is false now)
Program Example 3: The above program that will check the condition on the data entered from keyboard by a user.
Dim I As Integer
Dim J As Integer
I=InputBox(“Enter a value for I”)
J= InputBox(“Enter a value for J”)
If (I>J) Then
Print “Large Number is=”,I
End if
OUTPUT: …………
Here the output will depend on the values of I
and j.
1. If-Then-Else:
If-Then-Else statement is used to perform one action if the condition is true, otherwise perform another action in case the condition is false.
General Synatx:

If condition Then
Statement1
Else
Statement 2
End if
EXPLAINATION: Here statement1 is executed if the condition is true, if the condition is false then the statement2 is executed. The following program will explain this statement.
Program Example1: Start Visual Basic with standard Exe file, Place a command button on the form, and write the following code in click event.
(This program finds the maximum value of two values)

Dim I As Integer
Dim J As Integer
I=10
J=20
If (I>J) Then
Print “Larger Number is=”,I
Else
Print “ Larger Number is=”, J
End if
OUTPUT: Larger Number is=20
1. Nested If-Then-Else/ Nested Selection Structure:
When one If-Then-Else statement is the part of another If-Then-Else statement, then it is called Nested If-Then-Else Statement.
Nested If-Then-Else structure is used to handle multiple choices.
General Synatx:

If condition1 Then
Statement1
Else
If condition2 Then
Statement2
………………………
………………………
Else
If condition n Then
Statement n

End if
End if
End if


Program Example: Start Visual Basic with standard Exe file, Place a command button on the form, and write the following code in click event
(This program finds the largest/maximum value of three values)
Dim I As Integer
Dim J As Integer
Dim K As Integer
I=5
J=6
K=7
If I>J AND I>K Then
Print “Largest Number is=”,I
Else
If J>I AND J>K Then
Print “Largest Number is=”,J
Else
If K>J AND K>I Then
Print “Largest Number is=”,K
End if
End if
End if
OUTPUT: Largest Number is=7
SELECT CASE STATEMENT:
Like Nested If-Then-Else structure, the select case statement is also multiple selection structure. But it can handle multiple choices more efficiently.
General Syntax:
Select case Expression
Case Expression1
Statement1
Case Expression2
Statement2
………………………
………………………
Case Expression n
Statement n
Case Else
Statement
End Select
Note: Here the expression may be numeric or string expression.
Program Example1: Start Visual Basic with standard Exe file, Place a command button on the form, and write the following code in click event
Dim choice As Integer
Choice=InputBox(“Enter a number”)
Select case choice
Case 1,2,3
Print “Choice is in the range of 1……3”
Case 4,5,6
Print “Choice is in the range of 4…6”
Case 7,9,10
Print “Choice is in the range of 7…10”

Case Else
Print “ Invalid Choice”
End Select
Program Example2: Start Visual Basic with standard
Exe file, Place a command button
on the form, and write the
following code in click event
Dim month As string
month=InputBox(“Enter a month name of the year”)
Select case month
Case “March”, “April”, “May”
Print “Pleasant Season”
Case “June”, “July”, “August”
Print “Very hot Season”
Case “September”, “October”,“November”
Print “Normal Season”
Case “December”, “January”, “February”
Print “Very Cold Season”

Case Else
Print “ Invalid month of the year”
End Select
LOOPS
Loop: When a single statement or more statements are to be executed again and again, then we
use loop.
Types of Loops: Visual Basic supports three types of loops. They include
1. For -Next Loop
2. While-Wend Loop
3. Do-Loop
Now we explain them one by one as follow.
1. For Next Loop: For-Next Loop is used in a situation where we know in advance how many times a loop body has to be executed. For-loop is used for repetition of the loop body for a fixed number of times.

General Syntax:
The general syntax used for the For-Loop is as follow
For counter variable=Start value to End value [step n]
Loop body
Next counter variable
Where counter variable shows any numeric value. The startvalue represents the initial value of the countervarible. Endvalue represents the final value of the countervariable. The loop body consists of one or more statements that will be executed again and again.
The step value shows the change in increment. By default, the increment of countervariable is 1.
However, you can change it by change in stepvalue.
The keyword Next followed by countervariable is there to compare the countervariable (after stepvalue) with the Endvalue.
PROGRAM EXAMPLE-1:
Open Visual Basic with a Standard Exe file with a command button and write the following code in the click event of the button.
(This program displays Numbers from 1 to 10)
Dim I as integer

For I=1 To 10
Print I
Next I
To run this program, Press F5 and click the command button ,you will see the output as follow.
OUTPUT: 1
2
3
4
5
6
7
8
9
10
PROGRAM EXAMPLE-2:
Open Visual Basic with a Standard Exe file with a command button and write the following code in the click event of the button.
(This program displays Odd Numbers from 1 to 10)
Dim I as integer
For I=1 To 10 step 2
Print I
Next I
To run this program, Press F5 and click the command button , you will see the output as follow.
OUTPUT: 1
3
5
7
9
PROGRAM EXAMPLE-3:
Open Visual Basic with a Standard Exe file with a command button and write the following code in the click event of the button. (This program displays Numbers from 1 to 10 in descending order)
Dim I as integer

For I=10 To 1 step -1
Print I
Next I
To run this program, Press F5 and click the command button ,you will see the output as follow.
OUTPUT: 10
9
8
7
6
5
4
3
2
1
2- WHILE-WEND Loop.
The while wend loop is used in a situation where we do not know in advance how many times the loop body has to be executed.
General syntax
While codition
Loop body
Wend
Explaination: The While-wend loop starts with the keyword while followed by a test Condition. If the test condition is true, the loop body will be executed otherwise not. The loop body consists of statements that will be executed again and again. Then there is the keywords wend which finalizes the while wends statement.
PROGRAM EXAMPLE-1:
Open Visual Basic with a Standard Exe file with a command button and write the following code in the click event of the button.
(This program displays Numbers from 1 to 10)

Dim I as integer
I=1
While I <= 10
Print I
I=I+1
Wend
To run this program, Press F5 and click the command button , you will see the output as follow.
OUTPUT: 1
2
3
4
5
6
7
8
9
10
PROGRAM EXAMPLE-2:
Open Visual Basic with a Standard Exe file with a command button and write the following code in the click event of the button.
(This program displays Odd Numbers from 1 to 10)
Dim I as integer
I=1
While I<=10
Print I
I=I+2
Wend
To run this program, Press F5 and click the command button, you will see the output as follow.
OUTPUT: 1
3
5
7
9
PROGRAM EXAMPLE-3:
Open Visual Basic with a Standard Exe file with a command button and write the following code in the click event of the button.
(This program displays Numbers from 1 to 10 in
descending order)
Dim I as integer
I=10
While I >=1
Print I
I=I-1
Wend To run this program, Press F5 and click the command button , you will see the output as follow.
OUTPUT: 10
9
8
7
6
5
4
3
2
1
3-Do-Loop
Do-Loop is another type of loop. It is like while wend loop which is used to execute the loop body for an undermined number of times. It is post-test loop unlike the for-next and do while loops which are pre-test loops. Here the loop body must be executed at least once before the test condition is checked. If the test condition is true, the loop body will be executed for the next time otherwise not.
General Syntax
Do
Loop body
Loop While testcondition
OR

Do [{While |until} condition ]
Loop body
Loop
PROGRAM EXAMPLE-1:
Open Visual Basic with a Standard Exe file with a command button and write the following code in the click event of the button.
(This program displays Numbers from 1 to 10)
Dim I as integer
I=1
Do
Print I
I=I+1
Loop While I <= 10

To run this program, Press F5 and you will see the output as follow.

OUTPUT: 1
2
3
4
5
6
7
8
9
10
PROGRAM EXAMPLE-2:
Open Visual Basic with a Standard Exe file with a command button and write the following code in the click event of the button.
(This program displays Odd Numbers from 1 to 10)
Dim I as integer
I=1
Do
Print I
I=I+2
Loop While I<=10
To run this program, Press F5 and click the command button ,you will see the output as follow.
OUTPUT: 1
3
5
7
9
PROGRAM EXAMPLE-3:
Open Visual Basic with a Standard Exe file with a command button and write the following code in the click event of the button.
(This program displays Numbers from 1 to 10 in descending order)
Dim I as integer

I=10
Do
Print I
I=I-1
Loop While I >=1
To run this program, Press F5 and you will see the output as follow.
OUTPUT: 10
9
8
7
6
5
4
3
2
1
NESTED LOOP:
When one loop statement (For-Next, While-Wend or Do-Loop) is used within the body of another loop statement, then it is called nested loop.
In Visual Basic Nesting process can be done at many levels (For within For, For within Do-Loop or While wend loop).
PROGRAM EXAMPLE-1:
Open Visual Basic with a Standard Exe file with a command button and write the following code in the click event of the button.
Dim I as integer
Dim j as integer
Print “ I “, “ j “
For I=1 To 3
For j=1 To 3
Print I, J
Next I, J
To run this program, Press F5 and click the command button , you will see the output as follow.
OUTPUT: I J
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
PROGRAM EXAMPLE-2:
Open Visual Basic with a Standard Exe file with a command button and write the following code in the click event of the button.
Dim I as integer
Dim j as integer
Print “ I “, “ j “
For I=1 To 3
j=1
Do while j<=3
Print I, J
J=j+1
Loop
i=i+1
Next I
To run this program, Press F5 and click the command button , you will see the output as follow.

OUTPUT: I J

1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Difference among For-next, While-wend & Do-loop?
The For-Next Loop and While Wend loop are pre-test loops which means that in these loops first of all the test condition is checked if it is true, the loop body is executed otherwise not.
On the other hand, the do-loop is post-test loop in which the loop body is executed at least once after that the test condition is checked if it is true the loop body is executed for the next time.
Which loop is much better?
In real world most of the applications require the use of For-Next loop where we know in advance how many times a loop body has to be executed.. However, there are some situations where one does not know in advance that how many times a loop body has to executed like a hospital system where one does not know in the start of the day how many patients will be treated in the hospital to day.
OR
An air reservation system, where one does not know how many passengers will travel to day by a particular air reservation system to Dubai or London.
For these situations we either use While-wend loop or Do-loop.
Still it is a matter of taste, which loop you like you can use it.
Arrays
An array is a group of variables, which can store a group of homogeneous data items. An array is used to store multiple values.
Types of Array
There are mainly two types of Arrays.
1. One Dimensional Array.
2. Multi dimensional Array/Two dimensional Array.
Now we explain each one in more detail with examples.
i. One Dimensional Array

A one-Dimensional Array is used to store the data in vector from or list. For one- dimensional Array a single subscript (index) is used.
We use for-next loop to access each element of one-dimensional array.
Declaration of one dimensional array.
An array must be declared before using it in the program. The following syntax is used for declaration of one-dimensional array.
Dim ArrayName (Size) as Data type
e.g Dim a(3) as integer
Where a is the name of array, and 3 is the size of A i.e. the number of elements. Hence the above array will store four elements starting for index 0 to 3
The memory representation of the above array “a” is as follow.

0 1 2 3
In visual Basic, the index number of the first element may be other than zero.
e.g. Dim b(-2 to 2) as Integer

-2 -1 0 1 2
Program Example: Start Visual Basic with New Standard Exe Project.Place a command button on the from & Write the following code for the click event.
Dim a(4) as Integer
Dim I as Integer
For I=0 to 4
A (I)= InputBox(“Enter elements to array”)
Next I
Print “The array elements are”
For I = 0 to 4
Print A(I)
Next I
( ii ) Two Dimensional Array
A two dimensional Array is used to represent the data in a matrix form or tabular from.
For two-dimensional array, two sub scripts are used i.e. one is to generate the rows & the other to generate the columns.
We use nested for-next loop for the two dimensional array.
Declaration of Two-Dimensional Array

The general syntax is as follow
Dim Array name (Size, Size) as datatype
e.g. Dim a(2,2) As Integer
This declaration of two-dimensional Array “a” has three row and three columns
Program Example:- Start visual Basic with Standard Exe Project. Place a command button on the form and write the following code for its click events.
Dim a (2,2) As Integer
Dim r As Integer
Dim C as Integer
For C = 0 to 2
A (r , c) = Inputbox (“Enter Array elements”)
Next c,r
Print “The Array Elements are”
For r = 0 to 2
For c =0 to 2
Print a (r, c)
Next c, r

OUTPUT:
Now Press F5 to run the project and click the button. All values of the dimensional array will be displayed on the form.
Other types of array
Besides the one-dimensional and two-dimensional arrays, there are also other types of arrays which include:
(i) Variant Array
(ii) Dynamic Array
(iii) Control Array
Now we explain each one briefly as follow
i. Variant Array
It the type of Array is not defined at the time of declaration, then the default type will be variant. Such type of Array is called variant Array.
Declaration of variant Array
A variant Array can be declared as
Dim ArrayName (Size)
e.g. Dim b (4)
Here b is a variant Array of five elements
ii. Dynamic Array:
An array whose size can be changed is called dynamic array.
Declaration of Dynamic Array
A dynamic array can be declared as follow
Dim C ( ) as Integer
Before using array C, you must define its scope by using Redim statement as
Redim C (4)
Redim is also used to change the size of array.
e.g. Redim C (10)
When Redim statement is used with dynamic array then the previous stored data is lost (Redim resets all values as empty or Zero).
To stop the loss of data, the keyword preserve is used with Redim Statement as follow
Redim Preserve C(10)
Program Example:- Start visual Basic with Standard Exe Project. Place a command button on the form and write the following code for its click events.
Dim C ( ) as Integer
Redim C (4) as Integer, I as Integer
For I = 0 to 4
C (I) = InputBox ( “Enter the numbers”)
Next I
For I = 0 to 4
Print C (I)
Next I
Control Array
(iii) Control Array
When a visual basic application requires a group of option buttons or check boxes on the form, it is a good idea to use the control array. A control array is a group of controls that all have the same name. All controls in an array must be of the same class. An advantage of using a control array, rather then independent controls, is that the controls share one click event, you can use a case structure to determine which button or box is selected. The number inside the parentheses is called index and is used to refer to the specific control within the array. All subsequent controls given the same name will automatically have an index attached.
COLLECTION:
A collection is an alternate form of the array. The elements of array are accessed by using index number, but the elements of a collection are accessed by using key (unique for each element) as well as index number.
Declaration of Collection
A collection must be declared before using it in the program
General syntax for Collection Declaration is as follow
Dim Collectionname AS New Collection
e.g. Dim CityName AS New Collection
Methods of Collection:
A collection has the following four methods used
1. Add
2. Remove
3. Item
4. Count
Now we explain these methods as follow
1. Add( ):
The Add( ) method is used to add new elements into the collection.
The general syntax of Add ( ) method is as follow
Collectionname.Add value, key, Beforekey, Afterkey
e.g. CityName.Add “Peshawar”, “Key2”, “Key1”
Here the key2 is the key, and key1 is the beforekey.
You can use either the Before key or Afterkey.
ii) Remove ( ):
The Remove( ) method is used to remove or delete an element from the
collection.
The general syntax of Remove ( ) method is as follow
Collectionname.Remove(index)
Collectionname.Remove(key)
e.g. CityName.Remove(2)
CityName.Remove(“key2”)
1. Item( ):
The Item( ) method is used to view/display the elements of a collection.
The general syntax of Remove ( ) method is as follow
Collectionname.Item (index)
Collectionname.Item (key)
e.g. CityName.Item(1)
CityName.Item(“key2”)
1. Count:
The count method is used to return the total number of elements in the collection.The general syntax of Remove ( ) method is as follow
Collectionname.count
e.g. CityName.count
Program Example: Start Visual Basic with standard Exe file, place six command buttons on the form and set the properties for these controls as follow.
Control name Property Value
Form Window state 2-maximized
Command1 Caption Enter CityName in Collection
Command2 Caption Count Total elements in Collection
Command3 Caption Remove an item in Collection
Command4 Caption View an item of Collection
Command5 Caption View all elements of Collection
Command6 Caption View elements of collection using key
‘General Section
Dim CityName As New Collection
Dim C As Integer
Sub Form1_load ( )
C=0
End Sub
Sub command1_click ( )
Dim Cname As String
Cname=InputBox(“Enter new collection”)
CityName.Add Cname,”Key”+Cstr( C )
C=C+1
End Sub
Sub command2_click ( )
Print “Total Elements in Cityname=”CityName.Count
End Sub
Sub command3_click ( )
On Error Resume Next
Dim index as string
Index=InputBox (“Enter index to delete element”)
If index<1 or index>cityname.count then
MsgBox(“Invlaid Index number”)
Else
CityName.Remove(Val(index))
End if
End Sub
Sub command4_click ( )
On Error Resume Next
Dim index as string
Index=InputBox(“Enter index to delete element”)
If index= “ “ Then
Exit sub
End if
If index<1 or index>cityname.count then
MsgBox(“Invlaid Index number”)
Else
CityName.Item(Val(index))
End if
End Sub
Sub command5_click ( )
For each Cname in CityName
Print Cname
Next
End Sub
Sub command6_click ( )
On Error Goto Lab1
Dim key as string
key=InputBox(“Enter key to delete element”)
If key= “ “ Then
Exit sub
End if
If (CityName.count>1) then
Print CityName.Item(Key)
Else
Print “No Element Exists”
End if
Exit sub
Lab1:
MsgBox (“Key invalid”)
End Sub