Vbasic
Vbasic
ادخال البيانات.1
معالجة البيانات.2
استخراج النتائج.3
To solve a problem
Program
YouNeed
To create a program
Algorithm
YouNeed
To create an algorithm
Tools
YouNeed
To implement tools
programming Language
YouNeed
Visual Basic
1– Visual Basic Environment
1
Toolbox and Controls
Introduction
When creating your application, you add controls to it as you judge them
relevant for the possible assignments that can be performed on your
application. While working, you will deal with two big categories of
controls.
Controls Fundamentals
You as the developer will decide what control should be available in your
application, what functionality that control should provide, and what the
2
user can do with it. Some of the functionality is controlled by the
operating system because such functionality is part of the computer's
behavior. Some other aspects are under your control.
When creating your application, you will most likely start from a form.
Other controls are added to the form. To use one of them, you will get it
from an object called the Toolbox and then add them to the form. Once a
control is available to you, you can customize its appearance and
behavior.
Control Selection
To provide the necessary functionality for your application, you will use
controls from the Toolbox and add them to another component such as a
form. The control you pick up from the Toolbox is also referred to as a
child control. The control or object on which you add a child control is
referred to as its parent or host. This can be a form or another object that
has the capacity to host other controls.
To identify a control on the Toolbox, you can position the mouse on it. A
tool tip would appear.
To add a control to a host, on the toolbox, you can double-click it.
Alternatively, you can click the control on the toolbox and then "draw" it
on the host. You can keep adding controls to a host as necessary.
If you want to add a control over and over again, you can press and hold
Ctrl, click the control on the Toolbox, then draw it in the desired area on
the host. Every time you draw, the control would be added to the form or
host. Once you have added enough controls, you can release Ctrl.
If you select a control by mistake, you can simply click another. The new
one would become selected. If you clicked a control but don't want any
control at all, you can click the Pointer button. You cannot select more
than one control to add to a host.
Properties of Controls
Introduction
If you access a code when designing the application, it is said that you are
working at design time. If you access a control with code, it is said that
you are at run time. Therefore, design time refers to the form being
3
designed while displaying in Visual Basic. Run time refers to the time the
control is displaying to the user.
After adding a control to the application, you can customize it. For
example, you can change some parts of its appearance. You can also give
it assignments. These are done from two parts: the Properties window and
the Code editor.
Controls are broadly classified in two groups. A control is referred to as
graphical if the user can see it. There are other controls that will work
behind the scenes at run time. Such control are not graphical (an example
is the Timer). They can be referred to as static. The user never sees these
controls. There are some other controls not considered graphical because
the user cannot directly change their values. For example, a control that
displays only text (such is the case for the Label) is not considered
graphical.
A Windows control is an object that imitates a real world object. As such,
it is made of characteristics that define it. A characteristic is also called a
property. A property is any aspect that describes an object.
Once you have a control, you can change its properties in the Properties
window. This is considered that you are controlling the properties at
"design time". To change the properties of a control, first select it, then
proceed with changing the desired properties in the Properties window.
To control a form's properties with code, you will refer to itself. A form
refers to itself using the Me keyword. To change the properties of a
control with code, you refer to it by its name. Whether dealing with a
form or a control, after typing Me for the form, or the name of the
control, type a period. A list of the properties (and possibly other objects
that we will know eventually) will appear. You can continue typing or
simply select from the list. And continue with your coding. Not all
properties can be changed with code.
Controls Names
Everything on a computer must have a name. In the same way, to refer to
a control in your code, you must give it a name. When you add a new
control to your application, it receives a default name. When necessary,
which will be almost all the time, you should change that name to a more
recognizable one.
To change the name of a control, first select it. Then, in the Properties
window, click (Name) and type the desired name. Refrain from changing
the name of a control with code.
4
Properties, methods, and events
Properties of Controls
Naming Controls
The Control's Location
Control's Visibility
5
Visible property set to True. hide a control, set its Visible property to
False
Control's Availability
When a control is enabled, the user can click it or type in it. You can also
prevent this type of action by disabling the control
Tab Sequence
This means that, whether you click an object, type something using the
keyboard, move the mouse on the screen, or press and click at the same
time, a message is composed
Categories of Events
The Keyboard Events
The Click Event
The Double-Click Event
The Right-Click Event
The Focus Events
CountryName = ""
Boolean
Dim IsMarried As Boolean
IsMarried = False
Byte
Dim StudentAge As Byte
Integer
Dim MusicTracks As Integer
6
Decimal Data Types
A real number is one that displays a decimal part. This means that the
number can be made of two sections separated by a symbol that is
referred to as the Decimal Separator or Decimal Symbol. This symbol is
different by language, country, group of languages, or group of countries.
Single
A single is a decimal number whose value can range from –3.402823e38
and –1.401298e-45 if the number is negative, or 1.401298e-45 and
3.402823e38 if the number is positive
Double
This is used for a variable that would hold numbers that range from
1.79769313486231e308 to –4.94065645841247e–324 if the number is
negative or from 1.79769313486231E308 to 4.94065645841247E–324 if
the number is positive.
Dim Distance As Double
Currency
Dim StartingSalary As Currency
Date
Dim DateOfBirth As Date
Object
An Object is almost anything else that you want to use in your program.
Variant
A Variant can be used to declare any kind of variable. You can use a variant when you
can't make up your mind regarding a variable but, as a beginning programmer, you
should avoid it.
Here is a table of various data types and the amount of memory space each one uses:
7
Single 4-byte floating-point – 3.402823E38 to – 1.401298E – 45
number (negative values)
1.401298E – 45 to 3.402823E38
(positive values)
Double 8-byte floating-point – 1.79769313486231E308 to
number – 4.94065645841247E – 324 (negative
values)
4.94065645841247E – 324 to
1.79769313486231E308 (positive
values)
Currency 8-byte number with fixed – 922,337,203,685,477.5808 to
decimal point 922,337,203,685,477.5807
String String of characters Zero to approximately two billion
characters
Variant Date/time, floating-point Date values: January 1, 100 to
number, integer, string, or December 31, 9999
object. Numeric values: same range as Double
16 bytes, plus 1 byte for String values: same range as String Can
each character if a string also contain Error or Null values
value.
Boolean 2 bytes True or False
Date 8-byte date/time value January 1, 100 to December 31, 9999
Object 4 bytes Any Object reference
Constants
The Carriage Return-Line Feed Constant
vbCrLf
Operators
^,+,-,*,/,\ integer division,mod,&,_ line continuation
String concatination
dblResult = dblOperand1 + " " + dblOperand2
remarks
' This line will not be considered as part of the code
Rem I can write anything I want on this line
Logical operators
=,<>,<,>,<=,>=
NOT or and
If statement
8
Statement1
Statement2
Statementn
End If
If ConditionToCheck Then
Statement1
Else
Statement2
End If
If Condition1 Then
Statement1
ElseIf Condition2 Then
Statement2
ElseIf Conditionk Then
Statementk
End If
Loops Repeaters
Do
Statement(s)
Loop While Condition
Do Until Condition
9
Statement(s)
Loop
Do
Statement(s)
Loop Until Condition
A variable is said to be null when its value is invalid or doesn't bear any significant or
recognizable value.
Built-in Logical Constants: TRUE and FALSE
Message Boxes
MsgBox Message, [Buttons], [Title], [HelpFile], [Context]
Button Value Display
vbOKOnly 0
vbOKCancel 1
vbAbortRetryIgnore 2
vbYesNoCancel 3
vbYesNo 4
vbRetryCancel 5
10
Icon Value Description
vbCritical 16
vbQuestion 32
vbExclamation 48
vbInformation 64
Here is an example:
Private Sub Form_Load()
MsgBox "Are you ready for exam", vbYesNo Or vbQuestion
End Sub
11
vbDefaultButton2 256 The second button is the default.
vbDefaultButton3 512 The third button is the default.
The following MsgBox() function produces the message box shown in Figure 6.4:
12
First Program
Copy text
13
TextBox, Command Button, Label
TextBox Text1
Text=""
TextBox Text2
14
Text=""
TextBox Text3
Text=""
CommandButton Command1
Caption = "add"
CommandButton Command2
Caption = "subtract"
CommandButton Command3
Caption = "multiply"
CommandButton Command4
Caption = "divide"
CommandButton Command5
Caption = "end"
Label Label1
Caption = "first number"
Label Label2
Caption = "second number"
Label Label3
Caption = "result"
15
List Box
16
MsgBox "position is greater than the list"
Else
List1.AddItem Text1.Text, Val(Text2.Text)
Label1.Caption = "number of items = " + Str(List1.ListCount)
End If
End If
End Sub
End Sub
List1.columns = 0 | 1…n
List1.sorted = True | False
List1.visible = True | False
List1.Enabled = True | False
17
ComboBox
Styles
0 Combo Box
1 Simple Combo = textbox
2 Drop Down List
18
If found Then
MsgBox "Item is already in the list"
Else
Combo1.AddItem st
MsgBox "new item " & st & " was added"
End If
End Sub
19
CheckBox, Option, Scroll
20
Check1.Enabled = True
Command1.Caption = "DeActivate CheckBoxes"
End If
If Check2.Enabled Then
Check2.Enabled = False
Else
Check2.Enabled = True
End If
End Sub
21
Private Sub Option5_Click()
Text1.BackColor = vbYellow
End Sub
Checkbox Values
0 Unchecked
1 Checked
2 Grayed
Caption
Option
Caption
Value True | False
22
The Input Box
InputBox (prompt[, title][, default][, xpos][, ypos][, helpfile, context])
default String expression displayed in the text box as the default response if no
other input is provided. If you omit default, the text box is displayed empty.
23
Private Sub Command1_Click()
CD1.CancelError = True
CD1.ShowOpen
If Trim(CD1.FileName) = "" Then
MsgBox "Canceled By the User"
Else
fname = CD1.FileName
End If
' Read the file's contents into the control.
filenum = FreeFile()
Open fname For Input As #filenum
Text1.Text = Input$(LOF(filenum), filenum)
Close #filenum
24
last:
End Sub
CD1.CancelError = True
CD1.ShowOpen
If Trim(CD1.FileName) = "" Then
MsgBox "Canceled By the User"
Exit Sub
Else
fname = CD1.FileName
End If
Img1.Stretch = True
Img1.Picture = LoadPicture(fname)
last:
End Sub
25
Example
Dim i As Integer
Text2.Text = ""
26
If Text1.Text = "" Then
Exit Sub
Else
End If
Exit Sub
Else
End If
Exit Sub
Else
End If
If Option1.Value Then
End If
27
If Option2.Value Then
End If
If Check1.Value = 1 Then
End If
If Check2.Value = 1 Then
End If
If Check3.Value = 1 Then
End If
End If
Exit Sub
Else
stdt = CDate(Text3.Text)
28
End If
End If
deg(1) = Val(Math.Text)
End If
deg(2) = Val(Survey.Text)
End If
deg(3) = Val(Programming.Text)
End If
deg(4) = Val(Concrete.Text)
sum = 0
For i = 1 To 4
Next i
average = sum / 4
29
stdinfo = stdinfo + "Degrees for student " + Text1.Text + vbCrLf
End Select
CD1.Flags = cdlCFBoth
CD1.ShowFont
Text2.FontSize = CD1.FontSize
Text2.FontBold = CD1.FontBold
Text2.FontItalic = CD1.FontItalic
Text2.Font = CD1.FontName
30
Text2.Text = stdinfo
End Sub
End
End Sub
Exit Sub
End If
fname = ""
CD1.DefaultExt = "txt"
CD1.ShowSave
fname = CD1.FileName
Exit Sub
End If
31
fnum = FreeFile()
Close #fnum
End Sub
CD1.ShowPrinter
Printer.Print Text2.Text
Printer.EndDoc
End Sub
32
Picture box
End Sub
33
r=r/2
Next i
End Sub
End Sub
End Sub
34
Private Sub Command6_Click()
End
End Sub
Dim pi As Single
pi = 3.141
P1.Cls
Next i
P1.Scale
End Sub
35
Two Forms
Form1 subroutines
Private Sub Command1_Click()
Form2.Show
End Sub
36
Private Sub Command1_Click()
Text1.Text = Form1.Text1.Text
End Sub
End Sub
37
Built in Functions
Sin ()
Cos ()
Tan ()
Abs ()
Atn ()
Exp ()
Round(expression [,numdecimalplaces])
Fix () The difference between Int and Fix is that if number is negative,
Int returns the first negative integer less than or equal to number, whereas
Fix returns the first negative integer greater than or equal to number. For
example, Int converts -8.4 to -9, and Fix converts -8.4 to -
Int ()
Log ()Returns a Double specifying the natural logarithm of a number.
Logn(x) = Log(x) / Log(n) The following example illustrates a custom
Function that calculates base-10 logarithms:
Static Function Log10(X)
Log10 = Log(X) / Log(10#)
End Function
Rnd () Rnd[(number)]
The optional number argument is a Single or any valid numeric
expression.
Return Values
If number is Rnd generates
Less than zero The same number every time, using number as the seed.
Remarks
The Rnd function returns a value less than 1 but greater than or equal to
zero.
The value of number determines how Rnd generates a random number:
For any given initial seed, the same number sequence is generated
because each successive call to the Rnd function uses the previous
number as a seed for the next number in the sequence.
38
Before calling Rnd, use the Randomize statement without an argument
to initialize the random-number generator with a seed based on the
system timer.
To produce random integers in a given range, use this formula:
Int((upperbound - lowerbound + 1) * Rnd +
lowerbound)
Here, upperbound is the highest number in the range, and lowerbound is
the lowest number in the range.
Note To repeat sequences of random numbers, call Rnd with a negative
argument immediately before using Randomize with a numeric
argument. Using Randomize with the same value for number does not
repeat the previous sequence.
Sgn ()
If number is Sgn returns
Equal to zero 0
IsDate(expression)
IsNumeric(expression)
IsEmpty(expression) Returns a Boolean value indicating whether a
variable has been initialized.
IsNull(expression) Returns a Boolean value that indicates whether an
expression contains no valid data (Null).
Converting functions
CBool(expression)
CByte(expression)
39
CCur(expression)
CDate(expression)
CDbl(expression)
CDec(expression)
CInt(expression)
CLng(expression)
CSng(expression)
CStr(expression)
CVar(expression)
Function Return Range for expression argument
Type
40
String functions
LTrim(string)
RTrim(string)
Trim(string)
Left(string, length)
Right(string, length).
Mid(string, start[, length])
Len(string | varname)
LCase(string)
UCase(string)
Str() Asc() Chr()
Val()
date1, date2 Required; Variant (Date). Two dates you want to use in
the calculation.
Settings
The interval argument has these settings:
Setting Description
yyyy Year
q Quarter
m Month
y Day of year
d Day
41
w Weekday
ww Week
h Hour
n Minute
s Second
firstdayofweek Optional. A constant that specifies the first day of the week.
firstweekofyear Optional. A constant that specifies the first week of the year.
Settings
The firstdayofweek argument has these settings:
Constant Value Description
vbMonday 2 Monday
vbTuesday 3 Tuesday
vbWednesday 4 Wednesday
vbThursday 5 Thursday
vbFriday 6 Friday
vbSaturday 7 Saturday
42
The firstweekofyear argument has these settings:
Constant Value Description
Remarks
To Format Do This
Dates and times Use predefined named date/time formats or create user-defined
date/time formats.
Date and time serial Use date and time formats or numeric formats.
numbers
43
MyStr = Format(5459.4, "##,##0.00") ' Returns
"5,459.40".
MyStr = Format(334.9, "###0.00") ' Returns "334.90".
MyStr = Format(5, "0.00%") ' Returns "500.00%".
MyStr = Format("HELLO", "<") ' Returns "hello".
MyStr = Format("This is it", ">") ' Returns "THIS IS
IT".
44
Modules, Functions and Procedures
To create another sub routine, on the main menu, click Tools -> Add
Procedure...
Sub SquarePerimeter()
Dim dblSide As Double
Dim dblPerimeter As Double
45
dblSide = Form1.txtSide
dblPerimeter = dblSide * 4
Form1.txtPerimeter.Text = dblPerimeter
End Sub
dblSide = Form1.txtSide
dblArea = dblSide * dblSide
Form1.txtArea.Text = dblArea
End Sub
Introduction
End Function
Function RectPerimeter()
Dim dblLength As Double
Dim dblHeight As Double
46
dblLength = Form1.txtLength.Text
dblHeight = Form1.txtHeight.Text
dblLength = Form1.txtLength.Text
dblHeight = Form1.txtHeight.Text
dblHours = txtHours
dblSalary = txtSalary
txtResult = dblResult
End Sub
47
Dim FName As String
FName = "Albert Edou Nkoulou"
GetFullName FName
Caption = FName
End Sub
End Sub
Built-In Functions
Conversion Functions
Function
Name Return Type Description
Converts an expression into a
CBool Boolean
Boolean value
Converts an expression into Byte
CByte Byte
number
Converts and expression into a date
CDate Date
or time value
Converts an expression into a
CDbl Double
flowing-point (decimal) number
Converts an expression into an
CInt Integer
integer (natural) number
Converts an expression into a
CCur Currency
currency (monetary) value
CLng Long Converts an expression into a long
48
integer (a large natural) number
Converts an expression into a
CSng Single
flowing-point (decimal) number
CStr String Converts an expression into a string
String-Based Functions
Frames
49
Menu
50
Private Sub about_Click()
MsgBox "This is a menu driven program"
End Sub
51
r1 = x / 2
‘r2 = r1
one:
r2 = (x / r1 + r2) / 2 ‘Do
‘r1 = r2
If Abs (r1 - r2) >= 0.000001 Then ‘r2 = (x / r1 + r2) / 2
r1 = r2 Loop Until Abs (r1 - r2) < 0.000001
GoTo one
End If
Text2.Text = r2
Text4.Text = Sqr(Val(Text1.Text))
End Sub
Private Sub Command1_Click()
End
End Sub
52
Private Sub help_Click()
MsgBox "Sorry there is no help"
End Sub
53
ByRef ByVal
Scrollbar
Small change = 5
Largechange=20
Min=0, max=255
54
Dim x As Double
Dim y As Double
x = CDbl(Text2.Text)
y = CDbl(Text3.Text)
Call swap1(x, y)
MsgBox "x= " + Str(x) + " y= " + Str(y)
End Sub
55
color = RGB(HScroll1.Value, HScroll2.Value, HScroll3.Value)
If Option1.Value Then
Text1.ForeColor = color
Else
Text1.BackColor = color
End If
End Sub
56
b=t
End Sub
End Sub
57
58