Академический Документы
Профессиональный Документы
Культура Документы
Variable
A location in the computer's memory where data is stored. You can change the contents of a
variable but its name and storage area are reserved for use until you end the Visual Basic
session or release the variable. Variables have a name (the word you use to refer), a data type
(which determines the kind of data the variable can store) and value (to the value that variable
contains).
Variable Category
Category Name Description
Public/Global Variables declared using the Public Statement are visible to all procedures in
all modules in all applications. not just the ones they are defined in.
Private/Local A variable that is accessible only within a function or procedure. Other
procedures or functions cannot access this variable's data.
Variable Lifetime
A term for a variable that continues to exist after a function call or program is finished. Public
and static variables continue to exist, local variables do not.
Scope of Variables
The range of reference for an object or variable . For example, local variables can be
referenced only within the procedure they were defined. Public variables are accessible from
anywhere in the application.
Procedure-level Variables are private to the procedure in Not applicable. You cannot
which they appear. declare public variables within a
procedure.
Module-level Variables are private to the module in which Variables are available to all
they appear. modules.
Basic Programming Fundamentals
Visual Basic classifies the information mentioned above into two major data types, they are the
numeric data types and the non-numeric data types.
Variable Declaration
Declaring a variable means giving it a name, a data type and sometimes an initial value. The
declaration can be explicit or implicit.
Implicit Declaration
In implicit Variable declaration do not need to define variable type.Visual Basic adjust its
type according to the value you assign to it.Visual Basic use by default variable type is
variant.
Basic Programming Fundamentals
Explicit Declaration
Identifier Description
Dim Variables declared with Dim at the module level are available to all procedures
within the module. At the procedure level, variables are available only within the
procedure.
Private Private variables are available only to the module in which they are declared.
Public Variables declared using the Public statement are available to all procedures in all
modules in all applications
Global are available to all applications but Define in Module Level
Static Variables declared with the Static statement retain their values as long as the code
is running.
Example
Dim bA As Byte
Dim bolA As Boolean
Dim iA,iB,iC As Integer
Dim lA As Long
Dim sA As Single
Dim dA As Double
Dim daA As Date
Dim oA As Object
Dim strA As String
Dim strfA As String * 20, Dim vA As Variant 'Depend on Value
Static stA As Integer
Constants
A constant is a meaningful name that takes the place of a number or string that does not
change. you can't modify a constant or assign a new value to it as you can to a variable. There
are two sources for constants:
• Intrinsic or system-defined constants are provided by applications and controls. Visual
Basic constants are listed in the Visual Basic (VB) and Visual Basic
• Symbolic or user-defined constants are declared using the Const statement
To compute inputs from users and to generate results, we need to use various mathematical
operators. In Visual Basic
Conditional Operators
To control the VB program flow, we can use various conditional operators. Basically, they
resemble mathematical operators. Conditional operators are very powerful tools, they let the
VB program compare data values and then decide what action to take
Conditional Operators
Operator Definition Example Result
= Equal to 9 = 11 False
> Greater than 11 > 9 True
< Less than 11 < 9 False
>= Greater or equal 15 >= 15 True
<= Less or equal 9 <= 15 True
<> Not equal 9 <> 9 False
Basic Programming Fundamentals
Logical Operators
An operator that produces a logical result (true or false); sometimes called a Boolean operator.
Logical Operators
Operator Meaning Example Result
And Both sides must be true (9 = 9) AND (7 = False
6)
or One side or other must be true (9 = 9) OR (7 = 6) True
Xor One side or other must be true but not
both
Not Negates truth Not (9=9) False
Control structures allow you to control the flow of your program's execution. If left unchecked
by control-flow statements, a program's logic will flow through statements from left to right, and
top to bottom.
Decision Structures
Visual Basic procedures can test conditions and then, depending on the results of that test,
perform different operations.
• If...Then
• If...Then...Else
• Select Case
If...Then
Use an If...Then structure to execute one or more statements conditionally. You can use either a
single-line syntax or a multiple-line block syntax:
Single-line Syntax
If condition Then statement
IF...Then Examples
Private Sub cmdIF1_Click() Private Sub cmdIF3_Click()
a = 16 Dim number, digits As Integer
If a > 10 Then a = a + 1: Print a Dim myString As String
End Sub
number = InputBox("Please enter any
Private Sub cmdIF2_Click()
number.")
Dim number, digits As Integer
Dim myString As String
If number = "" Then Exit Sub
number = 53
If number < 10 Then
myString = "One"
If number < 10 Then
ElseIf number >= 10 And number < 100 Then
digits = 1
myString = "Two"
Else
ElseIf number >= 100 And number < 1000
digits = 2
Then
End If
myString = "Three"
Else
If digits = 1 Then myString = "One digit"
myString = "Un-Know"
Else myString = "More than one digits"
End If
Print myString
End Sub
If myString = "Un-Know" Then
Print myString & " number"
Else
Print "You press " & myString & " digit
number"
End If
End Sub
Private Sub cmdIF4_Click()
Dim Percantage As Byte
Cls
frmIF.FontSize = 15
frmIF.BackColor = &H8000000F
Percantage = InputBox("Enter your percantage to know grade.", "Grade Information")
If Percantage >= 80 And Percantage <= 100 Then
frmIF.BackColor = vbGreen
Print "Your Grade is A+"
Print "Percantage is " & Percantage & "%"
ElseIf Percantage >= 70 And Percantage < 80 Then
frmIF.BackColor = vbBlue
Print "Your Grade is A"
Print "Percantage is " & Percantage & "%"
ElseIf Percantage >= 60 And Percantage < 70 Then
frmIF.BackColor = vbYellow
Print "Your Grade is B"
Print "Percantage is " & Percantage & "%"
Basic Programming Fundamentals
ElseIf Percantage >= 50 And Percantage < 60 Then
frmIF.BackColor = &H8000000D
Print "Your Grade is C"
Print "Percantage is " & Percantage & "%"
ElseIf Percantage >= 40 And Percantage < 50 Then
frmIF.BackColor = &H80FF&
Print "Your Grade is D"
Print "Percantage is " & Percantage & "%"
ElseIf Percantage >= 30 And Percantage < 40 Then
frmIF.BackColor = &H40C0&
Print "Your Grade is E"
Print "Percantage is " & Percantage & "%"
Else
frmIF.BackColor = vbRed
Print "Your Grade is Fail"
Print "Percantage is " & Percantage & "%"
End If
End Sub
Select Case
A Select Case structure works with a single test expression that is evaluated once, at the top of
the structure. Visual Basic then compares the result of this expression with the values for each
Case in the structure. If there is a match, it executes the block of statements associated with
that Case:
Syntax
Select Case testexpression
[Case expressionlist1
[statementblock-1]]
[Case expressionlist2
[statementblock-2]]
..
[Case Else
[statementblock-n]]
End Select
Example
Private Sub cmdSC1_Click() Private Sub cmdSC2_Click()
Grade = InputBox("Enter your Grade.") age = InputBox("Enter your age")
Select Case UCase(Grade) Select Case age
Case "A" Case 18
MsgBox "Excellent" MsgBox "OOP! you young."
Case "B" Case 35
MsgBox "Good" MsgBox "Sorry!you are not young."
Case Else End Select
MsgBox "Need Work Hard" End Sub
End Select
Basic Programming Fundamentals
End Sub
Loop Structures
Loop structures allow you to execute one or more lines of code repetitively. The loop
structures that Visual Basic supports include:
• Do...Loop
• While …. Wend
• For...Next
• For Each...Next
Basic Programming Fundamentals
Do...Loop
Use a Do loop to execute a block of statements an indefinite number of times. There are
several variations of the Do...Loop statement.
Do...Until Examples
Private Sub cmdDoUntil1_Click() Private Sub cmdDoUntil2_Click()
'Natural Number 'Odd Number
Dim x As Integer Dim x As Integer
Cls Cls
x=1 x=1
Do Until x > 20 Do Until x > 20
Print x Print x
x=x+1 x=x+2
Loop Loop
End Sub End Sub
Private Sub cmdDoUntil3_Click() Private Sub cmdDoUntil4_Click()
'Even Number 'Table of 2
Dim x As Integer Dim x As Integer
Cls Cls
x=2 x=1
Do Until x > 20 Do Until x > 10
Print x Print "2 X" & x & "=" & 2 * x
x=x+2 x=x+1
Loop Loop
End Sub End Sub
Private Sub cmdDoUntil5_Click() Private Sub cmdDoUntil6_Click()
'Get Table Number From User 'Get Screen Font List
tbl = InputBox("Enter table number which Dim x As Integer
you want to generate.", "Get Table Number") Cls
If tbl = "" Then Exit Sub x = Screen.FontCount
Cls Do Until x = -1
x=1 Print Screen.Fonts(x)
Do Until x > 10 x=x-1
Print tbl & "X" & x & "=" & tbl * x Loop
x=x+1 End Sub
Basic Programming Fundamentals
Loop
End Sub
Private Sub cmdDoUntil7_Click()
Dim x, y, z As Integer
'Nested Loop
Cls
Print "X"; Space(5); "Y"; Space(5); "Z"
Print "--------------------------"
x=1
Do Until x > 3
y=1
Do Until y > 3
z=1
Do Until z > 3
Print x; Space(5); y; Space(5); z
z=z+1
Loop
y=y+1
Loop
x=x+1
Loop
End Sub
Loop...Until Examples
Private Sub cmdLoopUntil1_Click() Private Sub cmdLoopUntil2_Click()
'Natural Number 'Odd Number
Dim x As Integer Dim x As Integer
Cls Cls
x=1 x=1
Do Do
Print x Print x
x=x+1 x=x+2
Loop Until x > 20 Loop Until x > 20
End Sub End Sub
Private Sub cmdLoopUntil3_Click() Private Sub cmdLoopUntil4_Click()
'Even Number 'Table of 2
Dim x As Integer Dim x As Integer
Cls Cls
x=2 x=1
Do Do
Print x Print "2 X" & x & "=" & 2 * x
x=x+2 x=x+1
Loop Until x > 20 Loop Until x > 10
End Sub End Sub
Private Sub cmdLoopUntil5_Click() Private Sub cmdLoopUntil6_Click()
'Get Table Number From User 'Get Screen Font List
Basic Programming Fundamentals
tbl = InputBox("Enter table number which Dim x As Integer
you want to generate.", "Get Table Number") Cls
If tbl = "" Then Exit Sub x = Screen.FontCount
Cls Do
x=1 Print Screen.Fonts(x)
Do x=x-1
Print tbl & "X" & x & "=" & tbl * x Loop Until x = -1
x=x+1 End Sub
Loop Until x > 10
End Sub
Private Sub cmdLoopUntil7_Click()
Dim x, y, z As Integer
'Nested Loop
Cls
Print "X"; Space(5); "Y"; Space(5); "Z"
Print "--------------------------"
x=1
Do
y=1
Do
z=1
Do
Print x; Space(5); y; Space(5); z
z=z+1
Loop Until z > 3
y=y+1
Loop Until y > 3
x=x+1
Loop Until x > 3
End Sub
Do...While Examples
Private Sub cmdDoWhile1_Click() Private Sub cmdDoWhile2_Click()
'Natural Number 'Odd Number
Dim x As Integer Dim x As Integer
Cls Cls
x=1 x=1
Do While x <= 20 Do While x <= 20
Print x Print x
x=x+1 x=x+2
Loop Loop
End Sub End Sub
Private Sub cmdDoWhile3_Click() Private Sub cmdDoWhile4_Click()
'Even Number 'Table of 2
Dim x As Integer Dim x As Integer
Cls Cls
Basic Programming Fundamentals
x=2 x=1
Do While x <= 20 Do While x <= 10
Print x Print "2 X" & x & "=" & 2 * x
x=x+2 x=x+1
Loop Loop
End Sub End Sub
Private Sub cmdDoWhile5_Click() Private Sub cmdDoWhile6_Click()
'Get Table Number From User 'Get Screen Font List
tbl = InputBox("Enter table number which Dim x As Integer
you want to generate.", "Get Table Number") Cls
If tbl = "" Then Exit Sub x = Screen.FontCount
Cls Do While x <> 0
x=1 Print Screen.Fonts(x)
Do While x <= 10 x=x-1
Print tbl & "X" & x & "=" & tbl * x Loop
x=x+1 End Sub
Loop
End Sub
Private Sub cmdDoWhile7_Click()
Dim x, y, z As Integer
'Nested Loop
Cls
Print "X"; Space(5); "Y"; Space(5); "Z"
Print "--------------------------"
x=1
Do While x <= 3
y=1
Do While y <= 3
z=1
Do While z <= 3
Print x; Space(5); y; Space(5); z
z=z+1
Loop
y=y+1
Loop
x=x+1
Loop
End Sub
Loop...While Examples
Private Sub cmdLoopWhile1_Click() Private Sub cmdLoopWhile2_Click()
'Natural Number 'Odd Number
Dim x As Integer : Cls : x = 1 Dim x As Integer : Cls : x = 1
Do Do
Print x Print x
x=x+1 x=x+2
Basic Programming Fundamentals
Loop While x <= 20 Loop While x <= 20
End Sub End Sub
Private Sub cmdLoopWhile3_Click() Private Sub cmdLoopWhile4_Click()
'Even Number 'Table of 2
Dim x As Integer Dim x As Integer
Cls Cls
x=2 x=1
Do Do
Print x Print "2 X" & x & "=" & 2 * x
x=x+2 x=x+1
Loop While x <= 20 Loop While x <= 10
End Sub End Sub
Private Sub cmdLoopWhile5_Click() Private Sub cmdLoopWhile6_Click()
'Get Table Number From User 'Get Screen Font List
tbl = InputBox("Enter table number which Dim x As Integer
you want to generate.", "Get Table Number") Cls
If tbl = "" Then Exit Sub x = Screen.FontCount
Cls Do
x=1 Print Screen.Fonts(x)
Do x=x-1
Print tbl & "X" & x & "=" & tbl * x Loop While x <> 0
x=x+1 End Sub
Loop While x <= 10
End Sub
Private Sub cmdLoopWhile7_Click()
Dim x, y, z As Integer
'Nested Loop
Cls
Print "X"; Space(5); "Y"; Space(5); "Z"
Print "--------------------------"
x=1
Do
y=1
Do
z=1
Do
Print x; Space(5); y; Space(5); z
z=z+1
Loop While z <= 3
y=y+1
Loop While y <= 3
x=x+1
Loop While x <= 3
End Sub
Basic Programming Fundamentals
For...Next
When you know you must execute the statements a specific number of times, however, a For…
Next loop is a better choice. Unlike a Do loop, a For loop uses a variable called a counter that
increases or decreases in value during each repetition of the loop. The syntax is:
For counter = start To end [Step increment]
statements
Next [counter]
For … Each
A For Each...Next loop is similar to a For...Next loop, but it repeats a group of statements for
each element in a collection of objects or in an array instead of repeating the statements a
specified number of times. This is especially helpful if you don't know how many elements are in a
collection.
For Each element In group
statements
Next element
You can simplify programming tasks by breaking programs into smaller logical components. These
components called procedures
There are two major benefits of programming with procedures:
• Procedures allow you to break your programs into discrete logical units, each of which
you can debug more easily than an entire program without procedures.
• Procedures used in one program can act as building blocks for other programs, usually
with little or no modification.
Procedures Type
General Procedures
A general procedure tells the application how to perform a specific task. Once a
general procedure is defined, it must be specifically invoked by the application.
Event Procedures
When an object in Visual Basic recognizes that an event has occurred, it
automatically invokes the event procedure using the name corresponding to the event.
The syntax for a Sub procedure is:
[Private|Public][Static]Sub procedurename (arguments)
statements
End Sub
Calling Procedures
A procedure differs from a Function procedure in that a Sub procedure cannot be called by
using its name within an expression. A call to a Sub is a stand-alone statement. Also, a Sub does
not return a value in its name as does a function. However, like a Function, a Sub can modify the
values of any variables passed to it.
There are two ways to call a Sub procedure:
' Both of these statements call a Sub named MyProc.
Call MyProc (FirstArgument, SecondArgument)
MyProc FirstArgument, SecondArgument
Note that when you use the Call syntax, arguments must be enclosed in parentheses. If you
omit the Call keyword, you must also omit the parentheses around the arguments.
Visual Basic includes built-in, or intrinsic functions, like Sqr, Cos or Chr. In addition, you can use
the Function statement to write your own Function procedures.
The syntax for a Function procedure is:
[Private|Public][Static]Function procedurename (arguments) [As type]
statements
End Function
Basic Programming Fundamentals
There are three differences between Sub and Function procedures:
• Generally, you call a function by including the function procedure name and arguments on
the right side of a larger statement or expression (returnvalue = function()).
• Function procedures have data types, just as variables do. This determines the type of
the return value. (In the absence of an As clause, the type is the default Variant type.)
• You return a value by assigning it to the procedurename itself. When the Function
procedure returns a value, this value can then become part of a larger expression.
• Function return value but sub procedure don’t return any value
Function take argument but no return any 'Function take argument but no return any
value using ByVal value using ByRef
Private Function FunByVal(ByVal x As Integer) Private Function FunByRef(ByRef x As Integer)
x=x+5 x=x+5
End Function End Function
Private Sub cmdFun5_Click() Private Sub cmdFun4_Click()
Dim v1 As Integer Dim v1 As Integer
v1 = 30 v1 = 30
Print v1 Print v1
Call FunByVal(v1) Call FunByRef(v1)
Print v1 Print v1
End Sub End Sub
An array is a list of variables, all with the same data type and name. When we work with a single
item, we only need to use one variable. However, if we have a list of items which are of similar
type to use array. Arrays have both upper and lower bounds, and the elements of the array are
contiguous within those bounds. Because Visual Basic allocates space for each index number,
avoid declaring an array larger than necessary.
In Visual Basic there are two types of arrays:
• A fixed-size array which always remains the same size.
• A dynamic array whose size can change at run-time.
The format for declaring an array is:
Dim|Public|Private ArrayName([Subscript], [Subscript], [Subscript]) [As DataType]
- Dim, Public, and Private declare the array and its scope.
- ArrayName is the name of the array.
- Subscript is the dimensions of the array.
- DataType is any valid data type.
Variables of different data types when combined as a single variable to hold several related
informations is called a User-Defined data type.A Type statement is used to define a user-
defined type in the General declaration section of a form or module. User-defined data types
can only be private in form while in standard modules can be public or private.The Type
definition is basically a "template" on which other variables are defined; the template itself
does not store any data. To use a UDT, you must define a variable
The syntax for defining a UDT is:
Enums (enumerations)
Enums (enumerations) are structures you define when you need a set of constant values. An
Enum must be declared outside of any Sub Procedure and Function body. The elements of the
Enum type are initialized to constant values within the Enum statement. The assigned values
can't be modified at run time and can include both positive and negative numbers. the first
constant in an enumeration is initialized to the value 0, and subsequent constants are initialized
to the value of one more that the previous constant.
Syntax
[Public | Private] Enum name
membername [= constantexpression]
membername [= constantexpression]
. . .
End Enum
Example
Collection
A collection is a way of grouping a set of related items. Collections are used in Visual Basic to
keep track of many things, such as the loaded forms in your program (the Forms collection), or
all the controls on a form (the Controls collection).Visual Basic provides the generic Collection
class to give you the ability to define your own collections. You can create as many Collection
objects — that is, instances of the Collection class. Each Collection object comes with
properties and methods you can use to insert, delete, and retrieve the items in the collection.
Example