Vous êtes sur la page 1sur 24

Chapter-1

Snapshot
 Introduction to client/ server technology
 Front end tools – an introduction
 Programming process
 Visual basic integrated
Development environment
 Basic program structure

1.1 Introduction – Client Server Technology


Client-Server Architecture is a process, which involves a minim of two independent
entities, one being the Client and the other the Server. This architecture is used in multi-
user environment, where a single server serves multiple clients requests. In this process,
the client makes a request to the server. Server on the other hand receives the request,
processes it and sends the resulting output to the client. The request may be in the form of
SQL query or a request to file itself.
The data is processed in the Front end, but stored and served by the powerful Back Ends
like Microsoft Access, SOL Server and Oracle.

1.1.1 Client /Server Architecture consist of three components, each one focusing on a
specified job.
They are:
 A Database
 A Client Application
 A Network Connecting the Client and Server

Database Server
This component takes care of storing the clients information in a database, maintaining data
integrity and controlling database access.

Client Application
This component deals with the interface of the client application, performing validations
requesting and retrieving information to and from the database server.
Network
This components is the actual medium through which the data is transmitted between the
client and the server.

1.2 Front End Tools


Developed software must be user friendly and designed in such a way so as to meet the
objectives of the user. Since the packages are built for the users who may know anything
about the programming language.
The front – end tools helps to create such a GUI user friendly environment.
A front end is traditionally from based. A form is being used to capture and validate user
data. But it will not provide the method to store the data entered by the user. Visual Basic is
one of the commercial application’s Front End.

The computer programming is an extremely complex task made up many individual phases
all of which are important and all of which contribute to the solution of a problem.
The process of writing a program is called programming

1.3 Programming Process


Programs are used to solve the problems using computers. Computer programming is an
extremely complex task made up of many individual phases all of which are important and all
of which contribute to the solution of a problem.
The programming process is a set of activities that are carried out to develop and implement a
computer program.

1.3.1 Programming Methodology – Stages of Program Development


Developing a program involves different steps and each of these steps is important.
They are:

Defining a problem: The programmer generally omits this step. But this step is absolutely
necessary for creating a workable solution. Before working on a project the programmer
should fully understand what exactly the user wants to do.

Outlining the solution: The program is generally not doing a single task. A program is built
up of certain small modules. Many programmers write the different modules, it becomes
extremely important to specify both the responsibilities of each task and how these individual
task iterate and interact. So, it has to ensure that the pieces being developed separately are
integrated into a whole system.

Selecting and representing algorithms: The previous two steps are used to do the primitive
work of problem solving. The third step is to represent the problem in algorithmic way that is
designed by the programmer. This step is extremely important because it describes the details
of the proposed problem and it’s solution.

Coding: After defining a problem and sketching out the details of the algorithm the next step
is to code the process. Before doing the coding process the programmer has to choose a
computer language.

Debugging: The programmer has to locate and correct all the inevitable errors. This step is
time consuming and often tiresome.

Testing and validation: This is the most important step because the whole program is
useless unit it produces a correct result. After debugging a program the main job the program
gives the test that the result are correct and it does the same in all cases. Also the program
gives the proper error messages when the input data is wrong.

Program maintenance: The programs are not static in nature and they frequently become
outdated as errors are discovered, new problems need to be solved, reviews are needed when
new equipment becomes available. So, the development of the program may be done by one
programmer and the modification by another programmer. So, the programmer who is
involved in the modification has to read the code and has to understand it. So, the program
written should; well documented clear and systematic so that, any one can easily understand
it and do the modification.

1.3.2 Modular Approach


Modular programming refers to a technique in which logical parts of a problem are
divided into a series of individual routines so that each may be programmed independently.
Consider for instance, a program to process payroll file periodically. It can be split into 11
modules at three levels as shown.

 Process Employee
 Validate Payroll Transaction
 Create Payroll Cheque
 Create Current Week Error Listing
 Calculating Gross Salary
 Calculate Voluntary Deductions
 Process unmatched Employees
 Updated Master payroll file
 Update Master labour Distribution file
 Calculate
 Calculate mandatory Deductions
Each programmer, out of several at disposal can be entrusted with a module for writing and
testing thereby speeding up to the write up. The group leader can then combine these and test
the employee payroll file program.
A great advantage of modularized programming is that any changes in an application which
are bound to occur now and then affect only one or a few modules which can be modified at a
much lower cost than would have been the case for reprogramming in entirety.
The subroutines are those subsets of instructions amongst who are used with in a program.
These subroutines are used application and system programs. They are written once and for
all the computer manufactures or software agencies or the user himself.
Modules arise a section of a program into logical units just for the convenience of writing and
debugging. They may or may not appear over and again in the same program or different
programs. In other words, a subroutine is a module also but a module may or may not be a
subroutine.

1.3.3 Characteristics of a Good Program


The following important characteristics should be followed while writing a well program.

Accuracy: The accuracy of the calculation is essential in a computer program. It is also


referred to as integrity of a program. It should be clear that all other program enhancements
would be meaningless if the calculations are not carried out correctly. The main
characteristics of computer are the accuracy. The computer will always produce correct result
until and unless our logic is correct.

Clarity: Clarity refers to the overall readability of the program and it is important to give
emphasis on its underlying logic. If a program is clearly written. It should be possible for
another program to follow the program logic with ease.
Efficiency: Efficiency is an important characteristic of a program. It is concerned with
execution speed and effective memory utilization. Many complex programs require a trade
off between speed and memory utilization.
User Friendly: The end user who is using the software is not consulted with what is
happening inside the program. He requires the results. The program must be user friendly so
that the user can easily communicate with the program. Proper messages are to be given.
Whenever the required comments are to be written in the program.

Reliable: The program must be reliable that is it is able to handle the situations when the
wrong inputs are given.

Portable: The program which is written must be able to run on different platforms without
doing many changes.

1.4 Introduction to Visual Basic


Visual Basic has evolved from Basic Language. Visual Basic 6.0 is powerful application
development tool used to develop Client Server applications.
Visual Basic is the fastest and easiest way to create applications for Microsoft Windows. VB
provides complete set of tools to simplify rapid application development both for the
experienced professional and new Windows programmer.
In the name Visual Basic the “Visual” refers to the method used to create the Graphical
user interface (GUI) Unlike many language which require numerous lines of coding to
describe the appearance and location of interface elements. VB provides pre built objects that
can be used to form the Graphical User Interface. The elements that can respond to the
actions such as mouse click, double click, drag, droop etc are called the interface elements.

1.4.1 Features of VB
The compiler in Visual basic gives many different options for optimizing the
compiled code Such as optimization of fast Code. The Visual Basic is a very open
environment that supports the client/ Server architecture, Active X, Component Object Model
(COM), Distributed Component Object Model (DCOM). It also supports Open Database
Connectivity (ODBC).
A new feature that Microsoft calls IntelliSense enables the system to react in real time
during coding. There are five basic IntelliSense features. They are:

Quick Info is a feature that presents the syntax of the procedure. Which is being typed in a
Tool Tip like window. It even goes one step further in that it will bold the specific parameter
which is being coded in real time.

Complete word is a feature that automatically completes the word, which is typed in real
time, after enough characters that make the word distinct within the list of available words
has been typed.

Data Tips is the very useful feature that simply shows the value of the variable in a yellow
tool tip format at runtime.
List Constants is a feature that works the same as List Members feature except that with this
features available constant values for a given property are listed.

Some of the features are multiple projects can be loaded into the IDE-Integrated
Development Environment and treated as one. For example a standard project and an
ActiveX project can be loaded at the same time. This saves tremendous amount of time for
coding and debugging.

Here is a list of some other features:


Break point can be toggled simply with a mouse click.
Bookmarks can be place for quick location.
Properties in the property window can be manipulated alphabetically or even by category.
With a click of a mouse button all highlighted code will be commented or uncommented
Aligning and formatting can easily be applied to one or more controls.

1.5 Starting Visual Basic


 Standard EXE: It is a typical project type and used to create standard executable files.
 ActiveX EXE, ActiveX DLL: These types of projects are used to create ActiveX code
components, which are OLE automation serves. These two types are of projects
identical in functionality, but are packaged differently (as executable or Dynamic
Link Libraries).
 ActiveX Control: This type of project is used to create new ActiveX control.
 Data Project: It creates a project that automatically includes Data Report and Data
Environment.
 ActiveX Document EXE, ActiveX Document DLL: These project types are used to
create ActiveX documents, which are in essence Visual Basic applications that can
run in the Web Browser such as Internet Explorer.

The New Project dialog box has three tabs:


 New allows selecting new projects.
 Existing tab will enable to select an existing project and open it.
 Recent tab will enable to select and open the most recently worked projects during the
last few days.

1.6 Visual Basic IDE


Visual Basic Integrated Development Environment [VBIDE]
Like any other windows application, VB consists of multiple windows, which appear at
startup. The windows that are displayed when VB is started are collectively known as the
Visual Basic Integrated Development Environment (IDE).
IDE is a commonly used term to describe the environment we use to create an application.
Integrated Development Environment is an environment which consists of tools like
 Form
 Properties Window
 Code Window
 Project Explorer
 Tool Box
Using this we can build and compile the application easily and efficiently.

As shown in Figure the components of VBIDE are:


 Menu Bar
 Tool Bar
 Project Box
 Project Explorer Window
 Properties Window
 Form Designer Window
 Form Layout Window
 Object Browser

1.6.1 Menu Bar


The menu bar lists the menus that you can use in the active window. Besides the standard
File, Edit, View, Window and Help menu it also provides access to functions specific to
programming such as Project, Format & Debug. Menu Bar can modified using Commands
Tab of the Customize dialog box.

File Edit View Project Format Debug Run Tools Add-Ins Window Help

1.6.2 Tool Bar


Similar to other window applications VB has toolbars with the most commonly used
functions. The standard toolbar is normally visible in your workspace.
Rather than having to navigate the menus for certain commonly used commands the
programmer can select them from the toolbar

1.6.3 Tool box


The toolbox window contains all the components that are available to use in your project. The
set of controls available in the toolbox can be customized for each project. Toolbox displays
design-time controls. ActiveX controls, applets, HTML scraps , objects and text based on the
designer or editor you are to build a project. The tools are enabled only when the associated
designer or editor is active.

1.6.4 Project Explorer


This is simply a list of all the forms which make up the VB project.
Working with a single project can create many applications. As applications become more
complex it may be required to work with multiple projects in the same session of the
programming environment.
Example; First project to develop an application and second project to serve as a scrach pad
for testing code before you add to the application.

The project window tool bar contains three buttons, namely View code, View object and
Toggle Folders

View code Displays a window for writing Visual Basic Code


View object Display the form
Toggle Folders Toggles the forms folder

1.6.5 Property Window


The Properties Window displays the properties for a form or control Properties are artibutes
such as size, position, color etc.
The property window opens with the properties or events of the selected object displayed. If
more than one object is selected, the properties that are common are displayed.
Properties are listed either Alphabetically (Alphabetic order) or Categorized ( by category
such as Appearance, Behaviour, DDE, Fint etc).

Alphabetic Categorized

Form1 Form


(Name) Form1
Appearance 1-3D
Auto Redraw False
Back color &H8000000F&
Border Style 2-Sizable
Caption Form 1
Clip Control True
Control Box True
Draw mode 13-copy pen 

Caption
Returns/sets the text displayed in an object’s title bar or
below an object’s icon.

1.6.6 From Designer Window


Forms are added to the VB application as they are needed. They are the window which hold
the various controls (buttons, text boxes, etc) which make up the application.

   

1.6.7 Form Layout Window


Form Layout allows you to Visual positions your form at design time.

1.6.8 Code Window


As the name implies this is where the code that VB executes must be typed. Notice that the
heading of the window indicates with which event the code is associated.

1.7 CONTROLS
A control is an object that can be drawn on a form object to enhance user interaction with the
application.
The Tool Box Window contains various Controls. The Control or the objects placed in a form
at design Time. Select the Control with the Mouse the pointer, pointer changes to plus and
then draw in the form in the position wherever required.

Hint:
 Double Click on Control will place the Control at the center of the form. Then it can
be sized and moved to the requirement.
 Additional Controls can be added to the Tool Box by selecting the component menu
item in the project menu.
They respond to events initiated by the user or triggered by the system. They are classified
into 3 categories:

1.7.1 Standard Controls (appear by default in the Tool Box)

 Label
 Text Box
 Command Button
 List Box
 Combo Box
 Check Box
 Option Button

Label
A
A label is a graphical control used to display text and is normally used to identify controls
that do not have a caption property.
Properties
Name The name or ID to refer it in the code.
Caption TO set the text which is visible to the user. By default its value is name
given in “Name” property.
Auto Size Sets or retrieves the ability of a control to resize to fit the contents of the
caption property. It is a Boolean property. Default value is False
Alignment To position the text. By default it is Left Alignment.
Visible To Specify the Label should be Visible or not for the User.
It is a Boolean property. Default value is true.

Text Box
It is used to accept input from the user as to display the information to the user.
Properties.
Name Determines the name of the Text Box which is used to refer it in the code.
Text Returns or sets the text in the edit area of the Text Box
Max Length Determines the maximum number of characters that can be entered in the
box.
Default value is 0 and maximum is 32000 characters.
Multilane To invoke the Text Wrap Feature
Enabled Determines whether the Text Box should respond to user generated event.
Password Char Determines the character to be displayed when the password is typed.

Command Button
Command button is a control that is most commonly used in a user interface and is generally
used to initiate, interrupt or end a particular process.
Properties
Name The name or ID refer it in the code
Caption To set the text which is visible to the user. By
default its value is name given in “Name”
property
Example  Form 1
  

Label
LOGIN
Text Box
User Name
Command
Password Button
Ok Cancel

LOGIN: Property

Property Setting
Name 1-bllogin
Alignment 2-Center

Textbox (User Name): Property

Property Setting
Name Text name
Max Length 30
Text Empty

Textbox (Password): Property

Property Setting
Name Text pass
Max Length 6
Password Char *
Text Empty

Command Button (OK): Property

Property Setting
Name Cmdok
Caption OK

Hint : ‘&’ (ampersand) is to assign the access key

 Form 1   

CLICK ME
Property Setting
Name Cm click me
Caption CLICK & ME

List Box
A List Box is a control that displays a list of items from which the user can select one
or more items. If the number of items exceeds the display area of the list gets scroll bars
automatically.
To add items to the List Box at design item select the list property of the List Box and add
items to it. Press Ctrl+Enter after item is added.

Combo Box
Combo box is a control that contains both the features of a text box and a List Box.
This is used incases where the user can select an item from the list or selecting an item by
typing the text in the combo box.
There are three types of combo box
 Dropdown Combo (style 0)
 Simple Combo (style 1)
 Dropdown List (style 2)

Dropdown Combo
This type has an edit area with a down arrow button appears initially. The list items
are hidden until the user click the down arrow button. Once the user clicks the down arrow
buttons the list items are dropped down from which the user can select the required item. This
is the default combo box.

Simple Combo
This combo box displays the list items all the time. It displays an edit area with an
attached list box, which is always visible.

Dropdown List Combo


This type of combo box the user could click down arrow to view the list. The user can
select only one list item from this combo box.

Option Button
Option buttons or radio buttons appear in-groups. At any point of time the user can
select only one button. It is similar to toggle button. The main property of the option button is
checked and it is true if the control is checked it is false.

Check box
This presents one or more choices that the user can select, Main property of the
control is value and it is 0 if the checkbox is cleared and I if the checkbox is checked. This
also acts a toggle button.

ADO Data Control


If a database is not accessed, then this is not needed. If a database is accessed this control will
act as the interface to any other data bound control. The exception is that VB offers ways to
access databases directly from code but for modest display/edit applications the ADO Data
Control is very effective.

Dir List Box /Drive List Box /File List Box


These are almost always used in combination with each other. Often, however, the Common
Dialog Control will be used instead of these.
Line
It can be used as a static or it can be animated with the VISIBLE property and the MOVE
method.

B Shape
B When the line is not enough, this one supports rectangles anf ellipses/circles. As with the
line control, use its items to create animation.

OLE Container
If the object which come from other applications (such as Word, Excel,…….) is to be added
on to the VB application then this control is very useful.

Frame
It’s just a container- it can hold other controls. There are two very good reasons to use it. If
we want multiple groups of option buttons then place each group in a frame and each group
will operate independently. To manipulate control as a group (i.e., positioning then put them
in a frame and handle them all at one time.

Horizontal /Vertical Scroll Bar Controls


Basically we let use the slider value of a scroll bar as the input for other code that we write.
These are normally used in conjunction with other controls.

Timer
This is the most unusual of the intrinsic control. By setting the INTERVAL property this
control will automatically create an event on a regular basis. No other control does this!. This
can be used to create an action at a certain time and then turn the control off to prevent
repeats.

1.7.2 ActiveX (or) Custom Controls


MS common dialog control
MS flex grid control
MS Winsock control etc.
To ass a custom control:
 Select Project Components Select required control Click OK
 TO delete a custom control :
 Select Project Components Deselect required control Click OK

1.7.3 Insert table Objects


 MS Excel
 MS Word
 MS Power Point
 Paint Brush etc.
Insertable Objects are window application objects standard controls can be used only with
Visual Basic. Tab index property is to determine the control that would receive the focus
next, when a tab key is pressed.
All controls have the Properties, methods and events associated with them. The property of a
control refers to the characteristic appearance of the control with a value given. A method
refers to the functions associated with the controls. An Event refers to the action of a control,
which invokes a code to be executed.

1.8.1 Setting Properties


While creating an application is Visual Basic it passes through 3 distinct modes. They are
 Design mode
 Run mode and
 Break mode

Design mode is the mode in which most of the designing activities take place. When the
application is executing it is said to be in Run mode and when some error occurs while
execution the application enters into break mode.
Most of the properties of an object can be set at both Design time and run time. Some
properties can be set at design time by using properties window. There are some properties
that are not available at design time.

Setting Properties at Design time


Properties window is used to set properties of object at design time. These design time
properties are used ass initial setting when the application begins to execute. Some commonly
used design time properties are
Name, Caption, Enabled, Visible
Steps to set the property of an object at design mode
1. Place a control in the form Designer window by double clinking the required control
from the tool box.
2. Select the control for which you want to set the property by clicking once.
3. Pressing the key F4 displays window with properties for the selected control
4. Select the property you want to set.
5. Make changes to the property by selecting or typing the new property.
6. Make changes to the property by selecting or typing the new property.

Setting Properties at Run time


Property can be set to an object at run time through code with the following syntax
Object. Property=Expression

Examples
Setting run time property of textbox named-txt name

Txtname.Font.Italic=true
Txtname.Font.Size =24
Txtname.Font.= “Visual Basic”

These several lines can also replace with statement


With. Txtname
.Font.Italic=true
.Font.Size=24
.Text= “Visual basic”
End with
1.8.2 Form Properties
Form are the basic buildings of any application developed in Visual Basic. Forms have their
own unique properties. Each time when an application is opened in VB a new default form
with name Form 1 is added to the environment with default property setting. These default
property setting can be changed as required. The different form properties are:

Caption Determines the text which has to appear in the bar of the form
Name Specifies the name of the form, which is used to refer it in code.
Window State Normal, Maximized or Minimized.

1.8 Events & Methods


 An Event is basically an occurrence of some pre-defined action.
 Methods are the different actions that come associated with each control

Event Driven Programming


While programming in VB, the user may click a mouse on various controls or press a key
combination on the user interface. These are known as events. The application developer
must decide how the application must react to each of the user actions. This is called events
driven programming.
In VB the application does not determine the flow. Instead the events caused by the
user determine the flow of the application. The applications are to be programmed to react to
various external conditions known as events. Thus in VB applications the users actions
determine the applications flow. Hence VB is called an event driven programming.
An event is an action recognized by a form and control. Each form and control in Visual
basic has a predefined set of events. If one of these event occurs, Visual Basic invokes the
code in the associated procedure.

1.9.1 Events
A form or control receives an event.
The event can be caused
 By the user i.e. Keystroke
 By the system i.e. Timer Events
 By the code i.e. Load Event

Many events occur in conjunction with other events i.e. Mouse up, Mouse Down, Click
Events

Common Keyboard Events


KeyDown, Keyup
The Key down event is triggered when a key is pressed and Key Up event is
triggered when a key released.

Key Pres
To find which key was pressed. This event is frequently to write key events for textboxes
because this event takes place before the character is pressed or displayed in a textbox.

Change
The change event is triggered by various controls when their contents change.
Got Focus, Lost Focus
When the focus is moved from one control to the other, the first control receives the
Lost Focus event, and the second control receives the Got Focus event.

Example 1
Private sub text1 _ key press (Key ASCII as Integer)
End Sub

The Key Ascii argument is the ASCII character of the key pressed. The following event
allows the user to enter only numbers

Common Mouse Events


Click Dbl Click (Double Click)
Click event takes place when the user clicks the left mouse button and the Dbl Click
event takes place when the user double clicks the left mouse button.
Mouse Down, Mouse Up
Mouse Down when the mouse button is pressed.
Mouse up when the mouse button is released.

Mouse Move
This event takes place continuously as the mouse moves over the control.

1.9.2 Methods
Each control has its own independent set of method that helps us in performing
actions. Methods can be invoked only during runtime.

Cls method
Used to clear the form
Eg. Forml.cls

Print Method
VB prints the text form the top left corner (0.0)
Eg. Forml. Print “Welcome to Learn VB”

Hide Method
This method is used to hide the form off the screen.
Eg. Froml. Hide

Show Method
Show the form that is loaded in the memory on the screen.
 Load form
 Froml. show

List of Properties, Events and Methods

Properties Events Methods


Name Click Refresh
Appearance Drag Drop Drag
Back Color Drag Over Move
Back Style Got Focus Set Focus
Border Style Key Down Z Order
Caption Key Press OLE Drag
Causes Validation Key Up Show What’s This
Container Lost Focus
Enabled Mouse Down
Fore Color Mouse Up
Height OLE Complete Drag
Help Context ID OLE Drag Over
h Wnd OLE Drag Over
Left OLE Give Feed Back
Mask Color OLE Set Data
Mouse Icon OLE Start Drag
Mouse Pointer Validate
OLE Drop Mode
Parent
Right To Left
Style
Tag
Text
Top
Visible
What’s This Help ID
Width

1.9 Introduction – Programming


Visual Basic provides the Interactive User Applications Development Environment. This user
interactivity is provided by the Visual Basic controls. Actually controls are used to receive
user input and display out and have their own set of properties, methods and events. Coding
concentrates on Visual Basic controls and the ways of creating and implementing them. And
that is called ‘Programming’.

1.10.1 Anatomy of a Visual Basic program


The structure of a Visual Basic program is as follows:
1. Every Visual Basic program must be written within the Private sub (any event of
form or a control) and End Sub.
2. The End Sub statement is must for each Private statement.
3. A form or a control has a set of defined events and methods.
4. All the control statements like If.. end if etc. should be written within Private ..End
Sub

1.10 Data Types & Variables


 Data types Specifies the type of Input to generate the required Output
 Variable Named location in memory that can store a value.

i.e., The variable name allows the user to refer to the value in the variable and the data type
determines the type of data that the variable can store.
Eg. Rno as Integer
Variable Rno stores the value of rollno which is a numeric input

1.11.1 Data Types


When it is said an application, it needs to process some data to generate the required output,
where the data values need to be of different types.
Example: The application that deals with student
Student name - String data type
Mark - Integer data type

Data Type Example Description


Byte Dim tiny Number As Byte Store an integer in the range 0 to 255 (8 bits).
Boolean Dim finished As Boolean Stores a value that is either True or False.
Integer Dim counter As Integer Stores an integer (whole number) in the range
32768 to + 32767 (16 bits).
Long Dim long Number As Stores an integer in the range -2, 147,483,648 to
Integer +2,147,483,647 (32 bits)
Currency Dim cost As Currency Stores a real number in the range
922,337,203,685,477.5807
Single Dim gradient As Single Stores a single-precision floating point number
accurate to 8 significant digits (32 bits).
Double Dim atoms as double Stores a double –precision floating point number
accurate to 16 significant digits (64 bits0.
Date Dim today As Date Stores a Data
String Dim str Surname As String Stores a sequence of up to 63,000 characters.
Variant Dim unknown As Variant The data type will change depending on what
value is assigned to the variable. If not data type
is specified, this is the data type that will be used.

1.11.2 Variables
Variables are the placeholders in which data can be stored and is accessed whenever
required. In other words variables are named location in memory that can store a value.
A variable has two parts name and data type. It can store data of specific type. The variable
name allows the user to refer to the value in the variable and the data type determines the type
of data that the variable can store.

Rules for declaring a variable – A variable name:


 Must begin with a letter.
 Can contain only letters, numbers or the underscore character.
 Cannot have reserved keyword.
 Cannot contain hyphens.
 Must not exceed 255 characters.
 Must be unique within the same procedure or form.

Declaring Variable
General syntax for declaring a variable is
Dim < Variable name> As type
Eg: Dim Rno as integer
Dim name As String
o.e., Dim and As are keywords
The variable name is the “identifier”, used to identify the data.

The As clause of the Dim statement is optional. If no data type is specified to the variable, the
variable is allotted the Variant data type and initialized as Empty

1.11.3 Variant Variable


Variant variable are one of the most flexible data type because they can accommodate
all other types. A variable declared as variant is handled by Visual Basic according to its
current contents. If the integer values are assigned to a variant, visual basic treats it as integer,
if string values are assigned to a variant, it treats it as string type.

Example 1:
Dim b the variable b is variant type, can store any data such as

b=”One” String data type


b=1 Integer data type
Example2:
Dim speed
And later the code assigns the value to the variable as
Speed= “50.8”
The variable speed is now a string variable that can be used in statement such as the
following:
Msbox “The speed of the bus is” & speed & “km p hour”

The statement displays the results as shown below:

1.11.4 Constants
Constant refers to the value that will not be changed during the execution of a
program. Once a constant has been declared, its value cannot be changed in subsequent
statements. Usually the constants are processed faster than variables, because the compiler
automatically substitutes constant names with their values.

Declaring the constant variable is similar to the declaring the variables, except that in
addition to the constant variable name, a value must also be mentioned.

Const myarray[as type=value

Public const pi as double=3.141592.

1.11.5 Imlicit and Explicit declaration of variables


By default Visual Basic allows you to use variable without declaring it using a dim
statement. This is known as implict declaration. But this may lead to some error in the output,
which may not be detected due to some misspelled variables. These may also led to incorrect
output. This can be overcome by mentioning an option explicit statement in the declaration
section of each forms code window.

1.11.6 Scope of Variables


Variables declared with the Dim statement within a procedure exist only as the
procedure is executing. When the procedure finishes, the value of the variable disappears. In
addition, the value of a variable in a procedures is local to that procedure-that is, a variable
cannot be accessed in one procedure from another procedure. These characteristics allow
using the same names in different procedures without worrying about conflicts or accidental
changes.
The scope of a variable refers to the section of an application where the variable can be used.
There are three types of scope, a variable can have are local module and global.

Local Scope
A variable is said to have a local scope when it was decaled inside a function,
subroutine or an event. That is it can be accessed only within the function or procedure. The
value of variable is lost when the execution of procedure is completed.

Module Scope
A variable can be declared with module scope by using Private declaration statement.
The private declaration statement is the same as that of the Dim statement except the Dim
keyword is replaces with private keyword.

Global Scope
Global Scope variables are those variables that can be accessed in all procedures in all
modules of a project. Global Scope variables are declares using the Public keyword in the
general declaration section.

Scope of variable
Declaration
Type Used to declare variables in procedures. Each time the procedure is called, the data
stored in variables declared with this keyword are reset (eg. an Integer data
type will be reset to zero).

Static used to declare variables in procedures. Each time the procedure is called, the data
stored in variables declared with this keyword are retained.

Public used to declare variables within a module. The variable is available to all procedures
in the project.

Private Used to declare variables within a module. The variable is only available to
procedures within the project.
Re Dim The ReDim keyword is used to re-dimension an array.

1.11.7 There are other ways to declare variables:


 Declaring a variable in the Declarations section of a form, standard, or class module,
rather than within a procedure, makes the variable to all the procedures in the module.
 Declaring a variable using the public keyword makes it available throughout the
application.
 Declaring a local variable using the Static keyword preserves its value even when a
procedure ends.
 1.11.8 User-defiend data types
 User-defined data types are those data type that are defined by the user, which in turn
can contain one or more elements of any fundamental data type. These data types are
useful in case where a single variable record several related pieces of information.
User defined data type can be declared by using Type and End Type in General
Declaration section of the code module.

1.11.9 Operators
An operator is a symbol specifying an action that is performed on one or more
expressions. The different types of operators are:

Arithmetic operators: Operators that perform mathematical operations.

Operator Meaning
+ addition
- Subtraction
* Multiplication
/ Division
% (Modulo) Returns the remainder of a division

Comparison Operators: Operators which test whether two expressions are same or not

Operator Meaning
< Lesser than
> Greater than
= Equal to
<= Lesser than or Equal to
>= Greater than or Equal to
<> Not equal to

Logical Operators: Operators that evaluate some condition and returns True or False

Operator Meaning
AND Returns TRUE if both Boolean expressions are TRUE
OR Returns TRUE if either Boolean expressions is TRUE
Returns TRUE if both Boolean expressions are TRUE

1.12 Arrays
A standard structure for storing data in any programming language is an Array. Arrays
can hold sets of related data but the individual variables can hold single entities. Such as
a number, date or string. Arrays have upper and lower bounds and the elements have to
lie within those bounds.

Declaring Arrays
Unlike, simple variables arrays must be declared with the Dim statement followed by
the name of the array and the maximum number of elements it can hold in parentheses.
Dim sal (10)
In the above array, sal is the array that holds 11 values. Salary(0) is the first person
salary, salary 910 is the second person salary and so on.

There are two types of arrary:


 Fixed Size array
 Dynamic Array
Fixed Size Array
Fixes size array can be declared by giving a name to the array with the upper limit in
the parentheses. The upper limit should always be within the range of long data type.
Dim length (9) as Integer

In this case, the array will store 10 values, because the size of the array has been fixed.

Dynamic Array
There will be a situation when the user may not know the exact size of the array at
design time. Under such circumstances, a dynamic array can be initially declared and
elements can be added when needed instead of declaring the size of the array at design time.
With the use of the dynamic array it is possible to discard the data and return the resources it
occupied to the system, when it is no longer needed.

To create a dynamic array, declare it as usual with the Dim statement or public or private but
do not specify the dimensions.

Dim my array ()

Later in the program, depending on the number of elements to be stored in the array, the
ReDim statement can be used mention the actual size of the dimension.

ReDim my array (10)

When ReDim is executed, it forces the application to carry out an action at runtime. ReDim
statements are not executable and they can outside procedures.

Preserved keyword
Each time the ReDim statement id executed all the values currently stored in the array
are lost. Visual Basic resets the values of the elements as if they were just declared. The array
size can be changed without losing the existing data. The ReDim statement recognizes the
Preserve Keyword, which force it to resize the array without discarding the existing data.
For example user can increase an array without losing the values of the existing elements by
using the Ubound() functions.

Multidimensional Array
A multidimensional array is used when one needs to represent or store related information of
different dimensions. For example to hold the student registration number and marks of the
student, we need to mention the x and y co-ordinates.

Dim my array 910. 10)

It is possible to declare lower limits for one or both the dimensions as for fixed size arrays.
Dim my array 951 to 100, 1 to 50)

1.13 Control Structures


Control statements are used to control the flow or program execution. Visual Basic supports
control structures such as :
1. If … Then
2. If … Then … Else
3. Select … case
4. Do While … loop
5. Do … Loop While
6. For … Next

1.13.1 Decision Making Statements

If … Then Statement
If … then block is used for conditional execution of one or more statements
Dim a As integer
Dim b As Integer
a=5
b=5
if a = b Then
Ms Box “ both Values are Equal”
End if

If … Then … Else Statements


This gets executed only if the condition is true. The condition is usually a comparison. If …
then … Else block is used to define several blocks of statements. In order to execute one
block. The format is
If <Condition>then
<Statement>
Else
<Statement>
End if
Example: The code to display a message as which is the greatest of the given number.

Dim a As Integer
Dim b As Integer
Dim c As Integer

Private sub Form-Activate()


A = 7
B = 6
C = 8

If a > b Then
If a > c Then
MsgBox “A is greatest”
Else
If c > b then
MsgBox “c is greatest”
End If
End If
Else
If b > c Then
MsgBox “B is greatest”
Else
MsgBox “c is greatest”
End If
End If
End Sub

Select … Case Statement

Select … case statement is an alternative to If … then …else statement for selectively


executing a single block of statements from among multiple blocks of statements. The
Select .. Case statement tests a single expression, which is evaluated once at the top of case
structure. The result of the test is then compared with several values, and if it matches one of
them, the corresponding block is executed.

Dim color As integer


Private Sub From –Activate()
Color = 8
Select case color
Case 1
Debug . Print “Red Color”
Case 2
Debug . print “Green Color”
Case 3
Debug . print “Try Again”
End Select
End Sub

1.13.2 Looping Statement


Do while …. Loop.
This statement executes until the certain condition is met.

Dim Counter As Integer


Private Sub Form – Avtivate()
Counter = 3
Do While counter < 50
Counter = counter + 1
Loop
MsgBox “loop completed at” & counter
End Sub

DoLoop … while
This statement structure first executes the statement and then checks the condition after each
execution.

Dim counter As Integer


Private Sub Form –Activate()
Counter = 0
Do
Counter = counter + 1
Loop while counter < 10
Msgbox “loop completed at “ & counter

For … Next loop


This structure is used to count from a given number to a final number. These loops
helps to know how many times the statements in the loop will be executed. The following
code prints numbers from 1 to 10.
Dim I As Integer
Private Sub From _Active()
For I = 1 To 10 Steps 1
Debug. Print i
Next
End Sub

1.14 Modules
A module is a collection of Procedure, Function and Events. Collection of modules form a
project or an Application
There are three types of Modules
Form module : It contains the code in the form itself. The extension is FRM
Standard module : It stores the code which can be used at different locations within the
project. The Extension is BAS
Class module : It implements object oriented programming concept in Visual basic.
Can create new Objects, Methods, Properties and Events by writing
code in class module the extension is CLS

Advantages of using Modules


1. Maintainability of code
2. Easier to debug the program
3. Reusability of code

Procedures
The Visual Basic Programs can be broken into smaller logical components called
procedures. Procedures are divided into logical units. They act as a building block for other
programs with slight modifications. Procedures are useful for implementing repeated tasks,
such as frequently used calculations.
A procedure can be a
 Sub Procedure
 Property Procedure
 Function Procedure

1.14.1 Sub procedures


Sub procedure is placed in a standard class and form modules. Each time a procedure is
called, the statement between sub and end sub are executed.
Syntax: [private] or ]public] or [static]sub procedure name (arglist)]
Statements]
End sub

Arglist is a list of argument name separated by commas. Each argument acts like a variable
in the procedure.
Two types of procedures
1. General procedures
2. Event procedure.

General procedures
This is where several event procedures perform the same actions. It is a good programming
practice to write common statements in a separate procedure and thaen call them in the event
procedure.
To add a General procedure:
1. The code window is opened for the module to which the procedure is to be added
2. The Add procedure option is chosen from the Tools menu.
3. The name of the procedure is typed in the text box.

Event procedure
Event procedure is a procedure block that the actual name of the controls. 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. Event procedures are said to be
attached to forms and controls. An event procedure for a control combines the control’s
actual name, an underscore, and the event name. For instance, to write a command button
click event to to invoke procedure when it is clicked, the command_click() event is used.

Private sub Form_load()


Statement
End sub

Vous aimerez peut-être aussi