351cs64
Visual programming notes
UNIT 1
Variables:
Variables are used by Visual Basic to hold information needed by your application.
Rules used in naming variables:
No more than 40 characters
They may include letters, numbers, and underscore (_)
The first character must be a letter
You cannot use a reserved word (word needed by Visual Basic)
Variable Declaration
There are three ways for a variable to be typed (declared):
1. Default
2. Implicit
3. Explicit
If variables are not implicitly or explicitly typed, they are assigned the variant type by default. The variant data type is a special type used by Visual
Basic that can contain numeric, string, or date data.
To implicitly type a variable, use the corresponding suffix shown above in the data type table.
For example,
1. TextValue$ = "This is a string" , creates a string variable,
2. Amount% = 300, creates an integer variable.
There are many advantages to explicitly typing variables. Primarily, we insure all computations are properly done, mistyped variable names are easily
spotted, and Visual Basic will take care of insuring consistency in upper and lower case letters used in variable names. Because of these advantages, and
because it is good programming practice, we will explicitly type all variables.
To explicitly type a variable, you must first determine its scope.
There are four levels of scope:
Procedure level
Procedure level, static
Form and module level
Global level
Within a procedure, variables are declared using the Dim statement:
Dim MyInt as Integer
Dim MyDouble as Double
Dim MyString, YourString as String
Procedure level variables declared in this manner do not retain their value once a procedure terminates.
To make a procedure level variable retain its value upon exiting the procedure, replace the Dim keyword with Static:
Static MyInt as Integer
Static MyDouble as Double
Form (module) level variables retain their value and are available to all procedures within that form (module). Form (module) level variables are declared
in the declarations part of the general object in the form's (module's) code window. The Dim keyword is used:
Dim MyInt as Integer
Dim MyDate as Date
Global level variables retain their value and are available to all procedures within an application. Module level variables are declared in the declarations
part of the general object of a module's code window. (It is advisable to keep all global variables in one module.) Use the Global keyword:
Global MyInt as Integer
Global MyDate as Date
Constant:
The values that does not change during the program execution is called constant. example pi=3.14
Arrays:
Visual Basic has powerful facilities for handling multi-dimensional variables, or arrays. An Array is a collection of homogenous items with same name and
same datatype.
Arrays are declared in a manner identical to that used for regular variables.
To declare an array as you would a single variable, you use the following syntax:
Dim|Public|Private ArrayName(Subscript) As DataType
In this syntax,
Dim, Public, and Private are Visual Basic keywords that declare the array and its scope. If you use Dim, the array is private to the procedure in which it is declared.
Public makes the array visible from anywhere in the program, and Private (within the General section of a form or module) makes the array visible only to the form or
module in which it's declared. If you use Dim within a module's procedure, the array will be available to only that procedure, but if you use Dim in the module's
Declarations section, the array will be available to all procedures within the module. ArrayName is the name of the array.
Option base: When you declare an array, the first element of the array is usually 0 (zero). It's possible, however, to force the first element of an array to be 1. To do
this, insert the statement Option Base 1 in the General section of a module within your project. You have to do this only when you want the first element of your array
to be element number 1.
Subscript is the number of the highest element in the array. Remember that the first element in an array is usually zero, so if you declare an array in which Subscript
is 6, you'll have seven element positions and, therefore, seven elements.
As is the Visual Basic keyword that signifies a type declaration. DataType is any valid Visual Basic data type, such as Integer or Double.
Therefore, to declare an array of integers with five elements in it, you would use the following: Dim iMyArray(4) As Integer
To assign a value to each element in the array iMyArray, you would use the following:
iMyArray(0) = 9
iMyArray(1) = 342
iMyArray(2) = 2746
iMyArray(3) = 0
iMyArray(4) = 8901
Collections:
Visual basic has an object name collection,an ordered set of items that can be referred to as a unit. Collection doesnot need to have the same data
type.collection has three methods and one property.
Add method(Item,key,before,after)
Item(index)method:return an item by index or by key.
Remove(index)method
Count property:returns the number of items in the collection.
Syntax: dim mycollection as new collection
Procedures:
Procedures
Visual Basic offers different types of procedures to execute small sections of coding in applications.
Visual Basic programs can be broken into smaller logical components called Procedures. Procedures are useful for
condensing repeated operations such as the frequently used calculations, text and control manipulation etc.
The benefits of using procedures in programming are:
It is easier to debug a program a program with procedures, which breaks a program into discrete
logical limits.
Procedures used in one program can act as building blocks for other programs with slight
modifications.
A Procedure can be Sub, Function or Property Procedure.
Sub Procedures
A sub procedure can be placed in standard, class and form modules. Each time the procedure is called, the
statements between Sub and End Sub are executed.
The syntax for a sub procedure is as follows:
[Private | Public] [Static] Sub Procedurename [( arglist)]
[ statements]
End Sub
arglist is a list of argument names separated by commas. Each argument acts like a variable in the
procedure. There are two types of Sub Procedures namely general procedures and event procedures.
Event Procedures
An event procedure is a procedure block that contains the control's actual name, an underscore(_), and the
event name. The following syntax represents the event procedure for a Form_Load event.
Private Sub Form_Load()
....statement block..
End Sub
Event Procedures acquire the declarations as Private by default.
General Procedures
A general procedure is declared when several event procedures perform the same actions. It is a good
programming practice to write common statements in a separate procedure (general procedure) and then
call them in the event procedure.
In order to add General procedure:
The Code window is opened for the module to which the procedure is to be added.
The Add Procedure option is chosen from the Tools menu, which opens an Add Procedure dialog
box as shown in the figure given below.
The name of the procedure is typed in the Name textbox
Under Type, Sub is selected to create a Sub procedure, Function to create a Function procedure or
Property to create a Property procedure.
Under Scope, Public is selected to create a procedure that can be invoked outside the module, or
Private to create a procedure that can be invoked only from within the module.
We can also create a new procedure in the current module by typing Sub ProcedureName, Function
ProcedureName, or Property ProcedureName in the Code window. A Function procedure returns a value
and a Sub Procedure does not return a value.
Function Procedures
Functions are like sub procedures, except they return a value to the calling procedure. They are especially
useful for taking one or more pieces of data, called arguments and performing some tasks with them. Then
the functions returns a value that indicates the results of the tasks complete within the function.
The following function procedure calculates the third side or hypotenuse of a right triangle, where A and
B are the other two sides. It takes two arguments A and B (of data type Double) and finally returns the
results.
Function Hypotenuse (A As Double, B As Double) As Double
Hypotenuse = sqr (A^2 + B^2)
End Function
The above function procedure is written in the general declarations section of the Code window. A
function can also be written by selecting the Add Procedure dialog box from the Tools menu and by
choosing the required scope and type.
Property Procedures
A property procedure is used to create and manipulate custom properties. It is used to create read only
properties for Forms, Standard modules and Class modules.Visual Basic provides three kind of property
procedures-Property Let procedure that sets the value of a property, Property Get procedure that returns
the value of a property, and Property Set procedure that sets the references to an object.
Function Procedures (Visual Basic)
A Function procedure is a series of Visual Basic statements enclosed by the Function
and End Function statements. The Function procedure performs a task and then
returns control to the calling code. When it returns control, it also returns a value to the
calling code.
Each time the procedure is called, its statements run, starting with the first executable
statement after the Function statement and ending with the first End Function, Exit
Function, or Return statement encountered.
You can define a Function procedure in a module, class, or structure. It is Public by
default, which means you can call it from anywhere in your application that has access
to the module, class, or structure in which you defined it.
A Function procedure can take arguments, such as constants, variables, or expressions,
which are passed to it by the calling code.
Declaration Syntax
The syntax for declaring a Function procedure is as follows:
VB Copy
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function
The modifiers can specify access level and information regarding overloading,
overriding, sharing, and shadowing. For more information, see Function Statement.
You declare each parameter the same way you do for Sub Procedures.
Data Type
Every Function procedure has a data type, just as every variable does. This data type is
specified by the As clause in the Function statement, and it determines the data type
of the value the function returns to the calling code. The following sample declarations
illustrate this.
VB Copy
Function yesterday() As Date
End Function
Function findSqrt(ByVal radicand As Single) As Single
End Function
For more information, see "Parts" in Function Statement.
Returning Values
The value a Function procedure sends back to the calling code is called its return value.
The procedure returns this value in one of two ways:
It uses the Return statement to specify the return value, and returns control
immediately to the calling program. The following example illustrates this.
VB Copy
Function FunctionName [(ParameterList)] As ReturnType
' The following statement immediately transfers control back
' to the calling code and returns the value of Expression.
Return Expression
End Function
It assigns a value to its own function name in one or more statements of the procedure.
Control does not return to the calling program until an Exit Function or End
Function statement is executed. The following example illustrates this.
VB Copy
Function FunctionName [(ParameterList)] As ReturnType
' The following statement does not transfer control back to the
calling code.
FunctionName = Expression
' When control returns to the calling code, Expression is the
return value.
End Function
The advantage of assigning the return value to the function name is that control does
not return from the procedure until it encounters an Exit Function or End Function
statement. This allows you to assign a preliminary value and adjust it later if necessary.
For more information about returning values, see Function Statement. For information
about returning arrays, see Arrays.
Calling Syntax
You invoke a Function procedure by including its name and arguments either on the
right side of an assignment statement or in an expression. You must provide values for
all arguments that are not optional, and you must enclose the argument list in
parentheses. If no arguments are supplied, you can optionally omit the parentheses.
The syntax for a call to a Function procedure is as follows:
lvalue = functionname [( argumentlist )]
If (( functionname [( argumentlist )] / 3) <= expression ) Then
When you call a Function procedure, you do not have to use its return value. If you do
not, all the actions of the function are performed, but the return value is ignored.
MsgBox is often called in this manner.
Illustration of Declaration and Call
The following Function procedure calculates the longest side, or hypotenuse, of a right
triangle, given the values for the other two sides
Function hypotenuse(ByVal side1 As Single, ByVal side2 As Single) As
Single
Return Math.Sqrt((side1 ^ 2) + (side2 ^ 2))
End Function
The following example shows a typical call to hypotenuse.
Dim testLength, testHypotenuse As Single
testHypotenuse = hypotenuse(testLength, 10.7)
Passing Arguments by Value and
by Reference (Visual Basic)
In Visual Basic, you can pass an argument to a procedure by value or by reference. This is
known as the passing mechanism, and it determines whether the procedure can modify
the programming element underlying the argument in the calling code. The procedure
declaration determines the passing mechanism for each parameter by specifying the
ByVal or ByRef keyword.
Distinctions
When passing an argument to a procedure, be aware of several different distinctions
that interact with each other:
Whether the underlying programming element is modifiable or nonmodifiable
Whether the argument itself is modifiable or nonmodifiable
Whether the argument is being passed by value or by reference
Whether the argument data type is a value type or a reference type
For more information, see Differences Between Modifiable and Nonmodifiable
Arguments and Differences Between Passing an Argument By Value and By Reference.
Choice of Passing Mechanism
You should choose the passing mechanism carefully for each argument.
Protection. In choosing between the two passing mechanisms, the most important
criterion is the exposure of calling variables to change. The advantage of passing
an argument ByRef is that the procedure can return a value to the calling code
through that argument. The advantage of passing an argument ByVal is that it
protects a variable from being changed by the procedure.
Performance. Although the passing mechanism can affect the performance of
your code, the difference is usually insignificant. One exception to this is a value
type passed ByVal. In this case, Visual Basic copies the entire data contents of the
argument. Therefore, for a large value type such as a structure, it can be more
efficient to pass it ByRef.
For reference types, only the pointer to the data is copied (four bytes on 32-bit
platforms, eight bytes on 64-bit platforms). Therefore, you can pass arguments of
type String or Object by value without harming performance.
Determination of the Passing Mechanism
The procedure declaration specifies the passing mechanism for each parameter. The
calling code can't override a ByVal mechanism.
If a parameter is declared with ByRef, the calling code can force the mechanism to
ByVal by enclosing the argument name in parentheses in the call. For more information,
see How to: Force an Argument to Be Passed by Value.
The default in Visual Basic is to pass arguments by value.
When to Pass an Argument by Value
If the calling code element underlying the argument is a nonmodifiable element,
declare the corresponding parameter ByVal. No code can change the value of a
nonmodifiable element.
If the underlying element is modifiable, but you do not want the procedure to be
able to change its value, declare the parameter ByVal. Only the calling code can
change the value of a modifiable element passed by value.
When to Pass an Argument by Reference
If the procedure has a genuine need to change the underlying element in the
calling code, declare the corresponding parameter ByRef.
If the correct execution of the code depends on the procedure changing the
underlying element in the calling code, declare the parameter ByRef. If you pass it
by value, or if the calling code overrides the ByRef passing mechanism by
enclosing the argument in parentheses, the procedure call might produce
unexpected results.
Optional Parameters (Visual
Basic)
You can specify that a procedure parameter is optional and no argument has to be supplied for
it when the procedure is called. Optional parameters are indicated by the Optional keyword in
the procedure definition. The following rules apply:
Every optional parameter in the procedure definition must specify a default value.
The default value for an optional parameter must be a constant expression.
Every parameter following an optional parameter in the procedure definition must
also be optional.
The following syntax shows a procedure declaration with an optional parameter:
VB Copy
Sub name(ByVal parameter1 As datatype1, Optional ByVal parameter2 As datatype2 =
defaultval
Passing a Variable Number of Arguments
Here's another valuable technique: You can create procedures that can accept a varying number of arguments. You do that
with the ParamArray keyword in the argument list, which makes all the arguments passed at that point in the list and
after it part of an array. If you use a ParamArray argument, it must be the last argument in the argument list. Here's an
example; in this case, the ShowMessage Sub procedure is able to handle a variable number of arguments:
Module Module1
Sub Main()
End Sub
Sub ShowMessage(ByVal ParamArray Text() As String)
End Sub End Module
Error function
Returns the error message that corresponds to a given error number.
Syntax
Error [ (errornumber) ]
The optional errornumber argument can be any valid error number. If errornumber is a
valid error number, but is not defined, Error returns the string "Application-defined or
object-defined error."
If errornumber is not valid, an error occurs. If errornumber is omitted, the message
corresponding to the most recent run-time error is returned. If no run-time error has
occurred, or errornumber is 0, Error returns a zero-length string ("").
CONTROL FLOW STATEMENTS
Determinate Loops – Indeterminate Loops
Sometimes, the same statements will repeat multiple times. In that case, iteration structure is used. There are two
kinds of iteration structure:
1. Indeterminate loops and
2. Determinate loops.
][=-;p
In an indeterminate loop, don’t know how many times a loop will be executed.
Example: Do...Loop.
The determinate loop controls the number of times statements will be executed.
Example: For.......Next loop.
LOOP:
Visual Basic allows a procedure to be repeated many times as long as the processor until a condition or a
set of conditions is fulfilled. This is generally called looping. Looping is a very useful feature of Visual
Basic because it makes repetitive works easier. There are two kinds of loops in Visual Basic, the
Do...Loop and the For.......Next loop
1. Do Loop
The formats are
a) Do While condition
Block of one or more VB statements
Loop
b) Do
Block of one or more VB statements
Loop While condition
c) Do Until condition
Block of one or more VB statements
Loop
d) Do
Block of one or more VB statements
Loop Until condition
2. Exiting the Loop
Sometime we need exit to exit a loop prematurely because of a certain condition is fulfilled. The syntax to
use is known as Exit Do.
3. For....Next Loop
The format is:
For counter=startNumber to endNumber (Step increment)
One or more VB statements
Next
Sometimes the user might want to get out from the loop before the whole repetitive process is executed, the
command to use is Exit For. To exit a For….Next Loop, you can place the Exit For statement within the
loop; and it is normally used together with the If…..Then… statement.
Example 1
Do while counter <=1000
num.Text=counter
counter =counter+1
Loop
* The above example will keep on adding until counter >1000.
The above example can be rewritten as
Do
num.Text=counter
counter=counter+1
Loop until counter>1000
Example 2
Dim sum, n As Integer
Private Sub Form_Activate()
List1.AddItem "n" & vbTab & "sum"
Do
n=n+1
Sum = Sum + n
List1.AddItem n & vbTab & Sum
If n = 100 Then
Exit Do
End If
Loop
End Sub
Explanation
In the above example, we compute the summation of 1+2+3+4+……+100. In the design stage, you need to insert a
ListBox into the form for displaying the output, named List1. The program uses the AddItem method to populate the
ListBox. The statement List1.AddItem "n" & vbTab & "sum" will display the headings in the ListBox, where it uses the
vbTab function to create a space between the headings n and sum.
Example 3 a
For counter=1 to 10
display.Text=counter
Next
Example 3 b
For counter=1 to 1000 step 10
counter=counter+1
Next
Example 3 c
For counter=1000 to 5 step -5
counter=counter-10
Next
*Notice that increment can be negative
Conditions
Control Structures
1. If...Then...Else:
If condition1 Then
statements1
Else
statements2
End If
If condition1 is True, then statements1 block is executed; Else, condition1 is not True, therefore statements2 block
gets executed. The structure must be terminated with the End If statement.
The Else clause is optional. In a simple comparison, statements1 get executed or not.
2. If condition1 Then
statements1
End If
Example:
Private Sub OK_Click()
firstnum=Val(usernum1.Text)
secondnum=Val(usernum2.Text)
If total=firstnum+secondnum And Val(sum.Text)<>0 Then
correct.Visible = True
wrong.Visible = False
Else
correct.Visible = False
wrong.Visible = True
End If
End Sub