351cs64 Visual Programming Notes Unit 1 Variables:: Variable Declaration
351cs64 Visual Programming Notes Unit 1 Variables:: Variable Declaration
UNIT 1
Variables:
Variables are used by Visual Basic to hold information needed by your application.
Variable Declaration
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,
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.
Procedure level
Procedure level, static
Form and module level
Global level
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:
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:
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:
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:
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)
Remove(index)method
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.
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.
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.
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
default, which means you can call it from anywhere in your application that has access
VB Copy
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
The value a Function procedure sends back to the calling code is called its return value.
It uses the Return statement to specify the return value, and returns control
VB Copy
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
VB Copy
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
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.
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.
The following Function procedure calculates the longest side, or hypotenuse, of a right
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:
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.
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.
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.
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.
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.
Module Module1
Sub Main()
End Sub
Sub ShowMessage(ByVal ParamArray Text() As String)
Error function
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."
Sometimes, the same statements will repeat multiple times. In that case, iteration structure is used. There are two
kinds of iteration structure:
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.
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
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()
Do
n=n+1
Sum = Sum + n
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