Microsoft Visual Basic 6.0: Applied Science
Microsoft Visual Basic 6.0: Applied Science
Microsoft Visual Basic 6.0: Applied Science
Visual Basic
6.0
Applied Science
Second class
1. Introduction
Visual Basic implements graphical user interface that allows the use of
graphics for different applications. It provides visual interactive windows
with user, like Dialogue box for (color, font ...), Input box, and Output box.
Also it is able to create menu to simplify user application.
1
To exit from Visual Basic and return to Windows is like exit from most
Windows applications. There are three ways to close the Visual Basic as
stated below.
1- Click on close button icon that appears in the upper-left corner of the
screen.
2- Press Alt+F4
3- Select File >Exit
2
The IDE environment consists of many elements. Some elements are
displayed when Visual Basic is started (By default) as in the following
figure. Other elements are displayed if the user requires them. We will list
some of these elements.
a
b
c f
d
e
g
a- Menu Bar: It contains a standard command like: File, Edit,
View,Window, Help menus, and specific command such as: Project,
Format, or Debug menus.
3
f- Project Explorer Window: it is a list of the forms and modules for
thecurrent projects. lt is a hierarchical tree- branch structure, where the
project at top of tree and other parts like forms ,modules) descend from
this tree.
To Create an Application
The title of program includes the name of project, and when the user
first starts the program it takes a defaulted value (projectl).It also includes
resize icons. The following steps are required to create an application in
Visual Basic 6.0:
1- Select type of project New or Exciting. A form automatically appears in
the form design .The basis for any application's interface is the form
that user should create. User can add other forms to the project (to add
another form select project menu>add form).
2. To add objects (controls) to the form use the ToolBox.
3. Set the properties for the objects through properties window.
4
4. Write code. The Visual Basic Code consists of statements, and
declarations.
The code for an application can be written on the Code Editor window.
In this window user can view and edit quickly any of the code.
5. Run the Application. To run the application, click the Start button on
the toolbar, or press F5.
6. Stop. To stop running the application and return to visual basic program
click on stop button in tool bar.
7. Check if there is an error, return to step 3 ,otherwise continue.
8. Save project.
9. Exit.
Exercises
1-Define the following parameters:
a-Toolbar. b-ToolBox. c-Form
designer,
d-form layout. e-
project window,
f-properties window. i-
code editor window,.
2- Explain the advantage of the Visual Basic program.
5
Project
Project is a program designed to user application that may be simple
(like calculator program) or complex (like word program). Visual basic
program can create many types of projects. The most important or usual
project is the standard project (for window applications) and the DHTML
project (for internet).
a) To create project:
When program starts, project box appears-select Standard EXE >
Project window appears.
OR: File> New project> Box (select Standard EXE)> Project window
appears
Note: Usually first project runs first, but user can change that by:
Selecting project from project window > mouse list > Set as startup.
d) To delete a project:
Select project in Project window > Mouse list > Remove project.
6
e) To save project:
The visual basic can save the project on disc in two ways, as an
executable type or a non- executable type.
2- The form Files: this contains form description and any Object or
program related to it .This is saved with extension (.frm).
II- project for execution: This is the final stage so that it could be opened
and run by Windows and no need for Visual Basic program. File> Make
project.exe.
Item Action steps Remarks
Create New File>New project The user can open any number of
project projects.
Exist File>Open project Project was already designed and
saved.
Recent File>Open project Project was recently designed and
saved.
Save project File>Save project Visual Basic can deal with it (open
group as and modify).
File>Make projectl.exe For execution by window.
Delete project File> Remove project Select project before remove.
Forms
1) Introduction to form
The form is the most important visible object,without it no control can be
displayed. It is a window that can be designed and modified to fit user
applications. In the standard project the form Designer creates and
7
modifies visual forms .When user starts visual Basic program a form is
automatically displayed in Designer window. The designer can add any
number of forms to the project of his application by pressing: add form
from project menu.
There are two modes: design mode and running mode. User can
interchange between them, by pressing on start icon or stop icon
on tool bar.
2) Form properties
Properties list has a predefined value (numeric or string) and could
be changed, some properties could be rewritten like caption, and some
could be selected from option list by pressing on down arrow on the side.
Others could be rewritten or by browsing the computer files when
the user clicks on the dotted button on the right side a dialogue box
appears. The browsing button appears when the user clicks inside the box.
The most important properties of the form are listed in the following
table:
Property Objective code Stage of
name Changing
Name Used to represent name of form Design
in code
8
Caption String appear in title of form Formno..caption= "any name" Design and run
Backcolor Background color for form. Formno..Backcolor=Qbcolor(no.) Design and run
Forecolor Color of text written on form. Formno..forecolor=Qbcolor(no.) Design and run
Font Font style, type and size. Size: Formno..fontsize= no. Design and run
9
اختیار الكائن
فرة
ھنایتم كتاب ة الش
اسم الكائن نوع الحدث
5) Events:
Events are like electrical switches. The electrical switches are of
many types, so are the events.
The forms and controls support events (generation, interaction with
mouse and keyboard). The most important events for the form are
described in the following table.
Event Action taken when
Click Single click on object.
DbClick Double click on object.
load Loading the object
Examples:
1- Design a form such that: in event load, when project runs, the
form backcolor property changed (chose
any color). sol: code:
Private Sub Form_Load()
Form1.BackColor =
QBColor(12)
End Sub
Exercises:
Q1/ Design a standard project has three forms with backcolors red, blue
and green.
Q2/ design a standard project that has one form change the name from
form1 to "students"
10
Q3/ Create a standard project with one form the name of the project
"market seals" and the name of the form "stock markets" and save project
on desktop with name marketing .exe
Q4/ Design a standard project with four forms when running project all
forms appear on screen Note :use this code in form1 (form1.show,
form2.show, form3.show, form4.show)
11
Toolbox
It is a window box that contains tools which could be used in the
project. Tools are objects that could be selected from Toolbox to be placed
on form. To show the toolbox, Press toolbox icon > the toolbox appear as
in the following diagram.
10) List box : For a list, user adds to and deletes from this list. It takes
any size.
11) Horizontal Scrollbar : Create stand-alone Horizontal scroll bars.
12) Vertical Scrollbar : Create stand-alone vertical scroll bars.
13) Timer : Used to control object movement.
14) Drive List Box : It is a special ListBox filled automatically with names, of the
files in a specified directory. It is a list invariant.
15) Dir List Box : It is a special ListBox filled with drives (Hard disc, Flopy, CD) in
the system. It is an invariant.
16) File List Box : It is a special ListBox filled automatically with the names of all
DirListBox. It is a list invariant.
17) Shape : Used only to display rectangles, circles, and ovals on the forms. Never
raises any events
18) Line :Used only to display lines on the forms. It never raises any events.
19) Image : Used instead of PictureBox because it consumes fewer system resources.
20) Data : used for data base.
12
21) OLE : used for joining with another programs.
Tool Box and Form
The user can place the tool on form and then work with the tool. To place the
tool on form:
Click on tool >Draw tool to Form> the tool appears on Form.
Or: double click on it.
Notes:
a) Each tool has a property window .To see this window: Click on tool on
form>Property window appears.
b) Property can be changed manually or by code and the effect of code appears in
therun time (when user runs project). c) To put code for tool action:
Double click on tool > code sheet of the Form appears (with code of corresponding
tool is written) > User write the desired code inside tool event, or outside in Form
event.
Label:
It is used to display fixed text on form
Property
Objective Code Stage of Changing
name
Caption String appear on label labelno..caption= "any name" Design and run
Autosize To resize tool to fit text labelno..autosize= true or false Design and run
Backcolor Background color for label labelno..Backcolor=Qbcolor(no.) Design and run
Forecolor Color of text written on label labelno..forecolor=Qbcolor(no.) Design and run
Font Font style, type and size Size: labelno..fontsize= no. Design and run
13
Sol: the properties are:
Label1
caption Applied science
fontsize 14
Runningstage:
Textbox
The textbox is a box for entering and displaying text (characters or values) in
user project. This tool is used frequently in most of the application. The textbox has
property window, with no caption, but with space for text. The most important
property of this tool is the text content which is described in the following:
Property Stage of
Objective Code
name Changing
Text String appear on textbox text no.. text = "any name" Design and run
multiline To enter more than one line true or false Design
Backcolor Background color for textbox. text no..Backcolor=Qbcolor(no.) Design and run
Forecolor Color of text written on textbox. text no..forecolor=Qbcolor(no.) Design and run
Font Font style, type and size. Size: text no..fontsize= no. Design and run
italic
Style: font bold
underline
Type: label.FontName = "arial"
14
visible The textbox appear or disappear text no.visible= true or false Design and run
Enabled The textbox enable or disable. text no.. Enabled =true or false Design and run
passwordchar A row of symbols appear Textno.passwordchar=(symbol) Design and run
instead of letters
Setfocus Put the focus on the specified Textno.setfocus Run
textbox
Change text manually: change text property from property window, click
inside textbox and add text.
Sol: designstage
Form1
caption V.B
Text1
Label1 text Text1
Text2
Label2 Text Text2
Label1
caption username
Label2
caption password
Example: Design a form with one textbox, set the text properties so that this massage
appears when project runs (welcome to visual basic world).
15
Second method: by properties window
Text1
text Welcome to visual basic world
Runningstage
Text1
Command button
It acts as a switch. To deal with tool property> click on command button> property
window appear> change setting of any desired property. Usually change set its caption
property to a suitable string.
To make the button functional, the user should add some code. To do this: click on
command tool> code form appears with click event procedure. Write code in this
event or other events like press key event.
The most familiar properties that are needed for the command button are stated in the
table below.
Property
Objective Code Stage of Changing
name
Caption String appear on command commandno..caption="any name" Design and run
style Determine the of 1-graphical Design
style command 0-standard
Backcolor Background color fo commandno..Backcolor=Qbcolor( Design and run
command r no.)
Forecolor Color of text on commandno..forecolor=Qbcolor( Design and run
written command no.)
Font Font style, type and size Size: commandno..fontsize= no. Design and run
16
Type: commandno.FontName =
"arial"
visible The command appear or commandno.visible= true or false Design and run
disappear
Enabled The command or commandno.. Enabled Design and run
enable disable. =true or false
Example: Design a form with label, such that when click on the command button
"name" your name appears on label (at running stage). sol:
Label1
caption
Command1 Label1
caption name
Command1
PrivateSubCommand1_Click()
Label1.Caption = "Ahmad"
End Sub
Example: Design a form to appear your name and department in textbox, when click
on command button "name" and "department" respectively so that you can clear these
informations when click on command "clear" and stop project when click on
command "exit".
Text1
Command1 Command2
Command3 Command4
Text1
text
Command1
caption name
Command2
caption department
Command3
caption Clear
Command4
17
caption exit
Private Sub Command1_Click()
Text1.text="Muna"
End Sub
Example: Design a form contains two textbox so that when click on command button
"copy" the text copied from first textbox to the second textbox but in size (28).
Sol:
Text1
text
Text2
Text
Command1
caption copy
Private Sub Command1_Click()
Text2.Text = Text1.Text
Text2.FontSize = 28
End Sub
Atrunstagethiswindowappear
If the user enter by example the text (ABC) in first textbox and click on
command (copy) the same text appear on the second textbox but in size 28.
18
Exercise:
1- Design a form to display your name in specific color and size.
2- Write the following design steps with details
Shape: Shape is a tool used to draw geometric shape (circle, rectangle, square ,etc). It
has property window. It has no events like other tools (such as click, dblclick, etc.).
Property
Objective Stage of Changing
name
shape To determine a specific shape: Design and run
0-rectangle
1-square
2-oval
3-circle
4-rounded rectangle
5-rounded square
backstyle 0-trancsparence 1- Design
opaque
Backcolor colored the Background for shape, appear after Design and run
backstyle changed to value 1-opaque
bordercolor Colored the Border of shape Design and run
Example: Design a form contains a specific shape then write the name of this shape
on form.
19
Label1
caption circle Shape1
Shape1
shape 3- Label1
circle
List box: The user can't write directly in ListBox . He can add item to the ListBox
property or by code in the form.
Property Objective and code
name
sorted True , to sort the elements alphabetically
False , elements without sort.
Style To determine the style of list:
0-standard
1-checkbox
Clear list To clear all elements of the list:
Listno.Clear
Add items to list:
a) Change property list from properties window. When click on arrow, write
items (elements).
Example: Design a form contains label to display your department and two command
buttons "show" and "hide" such that when click on command1, form2 appears and
when click on command2, form2 disappears. In form2 design a list to contain the
name of departments branches which appears after click on command button
"display".
20
Form1
Label1:caption="appliedscience"
Command1:caption="show"
Command2:caption="hide"
Label1
Command Command
1 2
Form2
Command1:caption="display"
List1:list= فارغ
List1
Comman
Example: Design a form contains a sorted list alphabetically such that the user can
add the item from text to the list after click on command button "add".
Sol:
21
List1
list
sorted true
command1
caption add
Text1
text
Option button: Used only as a group of buttons. When the user selects one of them
the others are deselected automatically.
All other properties of this control are similar to those in form and command
button where they are fully discussed which are caption,
font, enabled, backcolor and visible beside an
option1:caption green important property
option2: caption blue which is value that
option3: caption red takes true or false and
it used with if
statement. The option button usually takes click event.
22
Example: Design a form with one text box and three check boxes such that when
click on boxes the following is done: change typing to bold, italic, underline.
Sol:
Text1
Text فا رغ Text1
Check1
caption Bold
Check2 Check1
caption Italic Check2
Check3
caption underline Check3
Run stage:
Timer
Timer returns the time in millisecond. It may be used to measure execution time of
code (program efficiency).
Property name Objective and code
interval To repeat the code according to event. It takes an
integer values (0-65535) and measured in millisecond
enabled timerno.. Enabled =true or false
Ex: design electronic clock to display the time in seconds.
sol:
23
Timer1
interval 1000
Label1 Label1
Caption
Private Sub
Timer1
Timer1_Timer()
Label1.Caption = Time
End Sub
Sol:
Timer1
interval 1000
enabled false Private Sub Command1_Click()
Label1
Caption العلوم
التطبیقیة
Command1 Label1
caption ابدأ
Timer1
Command
Timer1.Enabled = True
End Sub
Private Sub Timer1_Timer()
t = Rnd * 15
Label1.ForeColor = QBColor(CInt(t))
End Sub
Run stage:
When click on command button ابدأthe color of the font will be changed every second
randomly in integer no. (0-15).
24
And (Rnd) used to generate a random no. in a range (0-1)
a) Inputbox
Inputbox used to input value or characters for one variable from keyboard at running
stage.
This box needs a code in code sheet and could be written in any event or command
X=inputbox(" prompt or remark", "title")
vbquestion 32
vbexclamatio
48
n
vbinformation 64
The available commands for message box
structure value Commands
Vbokonly 0 Ok
Vbokcancel 1 Ok, Cancel
vbAbortRetryIgnor 2 Abort, Retry, Ignore
25
vbYesNoCancel 3 Yes, No, Cancel
vbYesNo 4 Yes, No
vbRetryCancel 5 Retry, Cancel
For example if we write the following statement then a message box will be appear as
shown below
or
MsgBox "please close your program", vbcritical, "Error"
or
MsgBox "are you sure you want to delete this file",vbQuestion+vbYesNo,"delete"
Sol:
Example: write a program to move the text (excellent) from textbox to message box
and change the color of the text after click on command button (display). Sol:
Text1: text="excellent"
Command1: caption=""عرض
26
Text1.Text=""
EndSub
Orwecanwritethefollowingcode:
Q2\design a form contains shape and command buttons "what is this" such that when
click on the command button the name of this shape appears in message box.
Q3/enter a text in label1 such that this text copied to label2 after click on command
button "copy" and delete from label2 after click on command button "delete".
Q4/ design a form contain command button such that when we click on command,
form2 will be appear and form1 will be disappear.
Q5/design a form "at run stage" the title of form1 will be change to "visual basic" and
the back color of form1 will change too.
Q6/design a form with two shapes, red and blue ,write code to replace the color every
between two shapes.
Q7/ design a form contain list box and two command buttons:
1- add: to add the element to the list from input box
2- delete: to delete the list elements
27
Visual basic statements
In visual basic program (code) there are four basic parts, i.e. it is contains
the following statements:
1- Declaration of variables and constants
2- Inputting variables
3- Operators for variables
4- Outputting variables
Variables
A variable is a space in memory filled with data (value, character, time
or date).
Notes:
- Variable name must start with character (not number or function) and
maximum length 256 character, and does not contain point or symbol. -
Variable name must not repeat for other values.
The variable has to be declared. Variable type is defined by its content .The
content may be data as numeric or character or string or Boolean or date, or
any type of data (called variant), these types declared as:
Note: The Dim declaration written in general part of the form or in any
place in form or sub procedure which used for one form. While Global
declaration used for all forms
The types of variables that are allowed in visual basic are stated in the table
below.
Types of variables
Type Value range Declaration
1-Integer -32768<x<32768 Dim x as integer
2-Long -2.1 e+009<x<2.1 e+009 Dim x as long
3-Single 1.4e-045 <|x|<3.4e+038 Dim x as single
28
4-Double 4.9e-324<x<1.79e+308 Dim x as double
5-String 65535 characters Dim x as string
6-Boolean True or false Dim x as Boolean
7-Date Computer time and date Dim x as date
Jan 100<x< 31 Dec 9999
Constants
It is a space in memory filled with fixed value that will not be changed.
Constant may be declared as: Const constant name = value
Example: Declare x as a constant (P), then compute the area of a circle. Put
suitable design.
Sol:
Form1
caption Area of a circle
label1
Caption radius
Text1
text
فارغ
Command1
caption compute
Enabled false
code stage:
Const p = 3.14159
Dim a, r As Single
29
There are methods to input variable x as stated in the following:
Method of input For all type of variable
In text tool X=textno.text
In input box X=inputbox("prompt","title")
Note: To enter many variables we usually use the second method with loop.
e2x Exp(2*x)/(cos(2*x)+sin(x))
cos(2 )x sin( )x
Assignment statement
There are many statements ways to fill a variable as follows:
Variable = expression
30
Expression may include variables, operations and functions as follows:
1- Numerical variable. For example: i=3
2- Mathematical relation. For example: x=a/b
3- Characters variable (string). For example: t="abc"
4- Boolean variable (logical). For example: p=true
31
On form Print x
Note: in load event we must use the statement:
(form1.show)
to text tool textno.text =X
to label tool Labelno.caption=x
By message box msgbox (x)
Or msgbox ("remark"& x)
The instruction print could be very helpful to display data and used as
follows:
Code Description example
print To leave one line and
print on next
Print "a", "b", "c" Use (,) to print a distance a b c
between outputs
Print "a"; "b"; "c" Use (;) to print the abc
outputs adjacent
Print "a","b"; Print a, b then print c on abc
Print "c" the same line
Example1: write a program to enter any text and compute its length. Put
suitable design. Sol:
Design stage:
Form1
Caption String length
Command1
caption Click here
Label1
Caption Length=
Text1
Text
Code stage:
Dim s As String
Private Sub Command1_Click()
s = InputBox("inter string")
L = Len(s)
Text1.Text = CStr(L)
End Sub
32
Runningstage:
Example2: write a program to add and subtract two integer numbers after
putting a suitable design. Use message box for outputting.
Design stage:
form
caption calculator
Command1
caption +
Command2
Caption -
Label1
Caption Enter no.1
Label2
Caption Enter no.2
text من خاصيةtext1, text2 ونفرغ
Code stage:
Dim x, y, z as integer
Private sub command1_click ()
X=val(text1.text)
Y=val(text2.text)
Z=x + y
Msgbox("addition result="&z)
End sub
Private sub command2_click ()
X=val(text1.text)
33
Y=val(text2.text)
Z=x - y
Msgbox("subtraction result="&z)
End sub
Running stage
Enter two values in text1 and text2. When click on command (+) or (-) the
Example3:writeaprogramtoexecutethefouroperationsaccordingtothe
Command
1
Comm
and2
Command
3
Command
4
Command6 Command
5
Codestage:
Dima,b,cassingle
addition or subtraction result appears in message box. following design.
Label1
Label2
Label3
34
Private sub command1_click ()
a=val(text1.text)
b=val(text2.text) c=a + b End
sub
Private sub command2_click ()
a=val(text1.text)
b=val(text2.text)
c=a - b
End sub
Private sub command3_click ()
a=val(text1.text)
b=val(text2.text)
c=a * b
End sub
Private sub command4_click ()
a=val(text1.text)
b=val(text2.text)
c=a / b
End sub
Private sub command5_click ()
Text3.text=cstr(c)
End sub
Private sub command6_click ()
Text1.text=" "
Text2.text=" "
Text3.text=" "
End sub
Design stage:
Dim x, y As Single
Private Sub command1_click()
x = Val(Text1.Text) y = Abs(x)
Text1.Text = CStr(y)
End Sub
35
Private Sub Command2_Click()
x = Val(Text1.Text) y = Sqr(x)
Text1.Text = CStr(y)
End Sub
Private Sub Command3_Click()
x = Val(Text1.Text) y = Int(x)
Text1.Text = CStr(y) End Sub
Private Sub Command4_Click()
x = Val(Text1.Text) y = Sin(x *
3.14159 / 180)
Text1.Text = CStr(y)
End Sub
Private Sub Command5_Click()
x = Val(Text1.Text) y = Cos(x
* 3.14159 / 180)
Text1.Text = CStr(y)
End Sub
Runningstage
Q2/Write a program to enter the name of a student and two marks of any
subject by input box then computes the average and display the name and
average in two labels.
Q3/ Write a program to enter a real number then find its square after putting
suitable design.
Q4/ Design a project with three forms, such that form1 contains two
command buttons "Pethagors equation" and "area of triangle" such that
when click on command1 "Pythagoras equation", form2 will be appear so in
this form the third side of triangle will be compute with Pythagoras equation
after enter the first and second side, and when click on "area of triangle" the
third form displayed so that the area will be compute after entering the base
and height. Use suitable output and input methods.
36
Q5/ Write a program to display the message below after click on command
button "run".
Q6/Write a program to display the time and the date, put a suitable design.
37
Menu
The menu is a bar at the top of the form. The standard form is
display without menu, but the user can add it. This menu could be
included in form using menu editor. In next section the menu editor and
the required code will be discussed.
Menu Editor
To use menu there are three ways:
1- Press menu icon from toolbar .
2- press (ctrl+E) from key board.
3- click on: tools>Menu Editor.
Menu editor box appears as shown below.
Moveitemdown Select
shortcut
Moveitemup
Add…
Remove…
38
To add many items
Clickonitem
39
Example: Design a form with menu and a label with a specific title. The
menu contains one item color with sub menu items: red, green, blue and
exit, to color the label in red, green, blue then exit from the program.
Sol: put label1 with any caption for example (hello)
Caption: color Create standard menu (color) from menu
Name: command1 editor>next
Caption: red Add sub menu items by pressing then enter
Name:command2 the caption and name>next.
Caption: green Do the same thinks for other items>ok
Name:command3
Caption: blue
Name:command4
Caption: exit
Name:command5
Shortcut: ctrl+E
40
Label1.backcolor=vbblue
End Sub
41
X= cint(text1.text) If x>= 50 then
text2.text= "pass" text2.fontsize=18 end if End sub
c) If.. Then.. Else structure: Used for running many programming
statements if the required condition satisfied. And running another
programming statements (after else) if the required condition not satisfied.
The general form is:
If condition then
Statements
Else
Statements
End if
Example 4: write a program to enter a user name and display the message
(hello) three times. The first one for (Muna), the second one for (Maha) and
the third for any user as a guest.
Sol:
Dim x As String
Private Sub command1_click() x =
Text1.Text
If x = "Muna" Then
MsgBox "hello, Muna"
ElseIf x = "Maha" Then
MsgBox "hello,Maha"
Else
MsgBox "hello, guest"
42
End If
End Sub
Example 5: Write a program to classify any entered number according to
its sign and display the phrase (negative number) when the number is
negative and the phrase (positive number) when the number is positive,
otherwise display the phrase (neither positive nor negative).
Sol:
Dim x As Single
Private Sub command1_click () x =
Val(Text1.Text)
If x > 0 Then
MsgBox "positive number"
ElseIf x < 0 Then
MsgBox "negative number"
Else
MsgBox "neither positive nor
negative"
End If
End Sub
Nested If statement:
It can be takes the following structure:
If condition then
If condition then
Statements structure2 structure 1
End if
End if
43
Dim a, b, c As Single Private Sub command1_click() a =
Val(Text1.Text) b = Val(Text2.Text)
If Option1.Value Then c = a * b
Text3.Text = CStr(c) Else
If b <> 0 Then
c=a/b
Text3.Text = CStr(c)
Else
Text3.Text = "illegal division operation"
End If
End If
End Sub
Select statement
Used for applying many statements depending on one variable. The
general form is:
Example 7: write a program to print the days of the week when we enter
its number Sol:
Dim x As Integer
Private Sub Command1_Click()
x = CInt(Text1.Text)
Select Case x
Case 1
MsgBox ("Sunday")
Case 2
MsgBox ("Monday")
44
Case 3
MsgBox ("Tuesday")
Case 4
MsgBox ("Thursday")
Case 5
MsgBox ("Wednesday")
Case 6
MsgBox ("Friday")
Case 7
MsgBox ("Saturday")
End Select
End Sub
mark evaluation
90-100 Excellent
80-89 Very good
70-79 Good
60-69 Medium
50-59 Pass
0-49 Fail
Dim x As Integer
Private Sub Command1_Click() x =
CInt(Text1.Text) Select Case x
Case 90 To 100
MsgBox ("excellent")
Case 80 To 89
MsgBox ("very good")
Case 70 To 79
MsgBox ("good")
Case 60 To 69
MsgBox ("medium")
Case 50 To 59
MsgBox ("pass")
Case 0 To 49
MsgBox ("fail")
Case Else
MsgBox "the range is 0-100", vbCritical, "error"
End Select
45
End Sub
Exercises
Q.1/ Design a form with three menus and label with a specific title.
The menus contain sub menus as follows: color: red, blue, green, style:
underline, bold, italic, size: 10, 20, 30 then write the code for each
command.
Q.6/ Design a form with a text box. Use select statement so that when
user enters g, b, r and y then form colored to green, blue, red, and yellow
respectively.
Loop statement:
Visual basic supports statement to perform loops. The loops statements could
have different structures as follows:
1- Counter loop.
2- Conditional loop.
1- Counter loop:
Loops apply programming statements for fixed number of times using counter
(for… next) statement.
46
Print "hello"
Next i
End Sub
Notes:
1-The variable's value that we use as counter must be integer value (integer, long).
2- If we don’t determined the step value then the assumed value is 1.
3- If the final value smallest than the initial value, then the step value must be
negative.
2- Conditional loop
Loops repeat programming statements according to specific condition. There are
two types of conditional loop:
1- Do while
2- Do until
1-Do while loop: In this loop the statements will be implemented and repeated when
ever the condition satisfied. The general form is:
Do while condition
Statements Loop
Example3: Write a program to print (hello) five times with its numbering using do
while loop.
Sol:
Dim i as integer
Private Sub Command1_Click ()
i = 1 Do while i <= 5
Print "hello"; i
i = i + 1 Loop
End Sub
47
i = 2 Do while i <= 10
Print i
i = i + 2 Loop
End Sub
2-Do until loop: In this loop the statements will be implemented and repeated when
ever the condition not satisfied, (i.e) the loop will be stopped when the condition
satisfied. The general form is:
Do until condition
Statements
Loop
Example5: Write a program to print (hello) five times with its numbering using do
until loop.
Sol:
Dim i as integer
Private Sub Command1_Click ()
i = 1 Do until
i>5
Print "hello"; i
i=i+1
Loop
End Sub
Example6: Write a program to find the summation of undetermined number of
positive numbers such that the program will be stopped when we enter negative
number.
Sol:
Dim x, sum As Single
Private Sub command1_click()
sum = 0
x = Val(InputBox("enter x", "summation"))
Do While x >= 0
sum = sum + x
x = Val(InputBox("enter x", "summation "))
Loop
MsgBox(CStr(sum))
EndSub
48
Example7: Write a program to find the summation of the numbers from 5 to 15.
Sol:
Dim I, sum as integer
Private Sub command1_click ()
sum = 0
For i = 5 to 15
Sum = sum + i
Next i
Label1.caption = "sum ="&cstr(sum)
End Sub
Running stage:
For example if we entered the numbers: 1, 5, -1, 3, 2, 0, -1, 3, 0, -4 then sum=8
Example9: Write a program to find the average of n numbers.
Sol:
Dim i as integer
Dim x, sum, av as Double Private Sub
command1_click () i = 1: sum = 0
n = cint (text1.text)
Do while i <= n
x = val(inputbox ("enter number"))
Sum = sum + x i = i + 1
Loop
Av = sum/n
Text2.text = cstr(av)
End Sub
49
Print i
i = i + 5 Loop
End Sub
Example11: write a program to find the average of numbers that dividable by 3 (with
out remainder) from 3 to 99.
Sol:
Dim I, n, sum as integer
Dim av as Double
Private Sub command1_click ()
i=3:n=0
sum = 0
Do while i <= 99
Sum = sum + i i
=i+3
n=n+1
Loop
Av = sum/n
Print "av ="; av
End Sub
Example12: write a program to print (welcome) ten times, the first one with the
ordinary size and color. Then make the color changed and the size bigger at each time.
Sol:
Dim i As Integer
Private Sub Command1_Click()
Print "welcome"
For i = 1 To 9
FontSize = 10 + i
ForeColor = QBColor(i)
Print "welcome"
Next i
End Sub
Series:
To compute the value of series, we use suitable loop statements according to the
boundaries (limits) of each series.
Example13: Find
Sum=1+x+x2+x3+…+xn , where x is an integer.
Sol:
Dim I, n, x, sum as integer Private Sub
command1_click () sum = 1
n=cint(text1.text) x=val(text2.text)
50
For i = 1 To n
Sum = sum +x^i
Next i
Text3.text=cstr(sum)
End Sub
Nested loop:
The nested loops are the loops that are placed inside each other. The most inner
loop will be executed first, then the outer ones. These loops should neither intersect,
nor have the same index. As follows:
For i = 1 To n
For j = 1 To m
Statements
Next j
Next i
Example14: write a program to print the multiplication table.
Sol:
Dim I, j As Integer
Private Sub command1_click()
For I = 1 To 10
For j = 1 To 10
p=I*j
Print I; "*"; j; "="; p,
Next j
Print
Next I
End Sub
51
Sol:
Dim I, j As Integer
Private Sub command1_click()
For I = 1 To 5
For j = 1 To i
Print j;
Next j
Print
Next I
End Sub
Exercises:
Q.1: write a program to find n factorial (n!)
Q.2: write a program to enter n numbers and find the average of negative numbers
only.
Q.3: write a program to print the multipliers of 6 from 12 to 60, using do while first,
then use do until loop secondly.
y1 x x2 x3
xn
Q.7: How many multipliers of 3 are there between 1 and 100? Write a program to find
that.
52