0% found this document useful (0 votes)
11 views

software-development-with-visual-basic

The document provides an introduction to Visual Basic, detailing its event-driven programming capabilities and the Integrated Development Environment (IDE) components such as the Menu Bar, Toolbox, and Project Explorer. It explains how to start a new project, navigate the IDE, and utilize various controls for building applications. Additionally, it covers the differences between Single Document Interface (SDI) and Multiple Document Interface (MDI) environments in Visual Basic.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

software-development-with-visual-basic

The document provides an introduction to Visual Basic, detailing its event-driven programming capabilities and the Integrated Development Environment (IDE) components such as the Menu Bar, Toolbox, and Project Explorer. It explains how to start a new project, navigate the IDE, and utilize various controls for building applications. Additionally, it covers the differences between Single Document Interface (SDI) and Multiple Document Interface (MDI) environments in Visual Basic.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 118

lOMoARcPSD|42888207

Software Development with Visual Basic

Master of business administration (Periyar Maniammai University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Logesh krishnan ([email protected])
lOMoARcPSD|42888207

UNIT-I
Introduction To Visual Basic
 The Visual Basic is an event driven programming language. The “Visual” part refers to the method used
to create the Graphical User Interface (GUI). The “Basic” part refers to the BASIC language.
 It is derived from the original BASIC language. It is the medium for developing windows based
application.

Entering Into VB 6.0


 In windows, click start, point to programs, point to the Microsoft Visual Studio and point to Microsoft
Visual Basic 6.0.
 Invoke Visual Basic 6.0 by either double clicking on the shortcut path or by going through the pull-up
menu from start.
Starting A New Project
 After invoking the VB 6.0 the new project dialog box will appear. It contains number of icons along
with the types of properties. To accept the default new project [Standard EXE] click Open or Enter key.
 It consists of three Tabs. They are:
o New
o Existing
o Recent
New:
 It is the current tab used to open the new project file.
Existing:
 It is used to display the existing projects on your screen.
Recent:
 It is used to display the projects on which you have recently worked.
 To start a new project always by open the File menu and click the “New Project” item (Ctrl+N). This
will again bring up a new project dialog box. Click on the item marked Standard EXE in the New
Project window.

Integrated Development Environment:


IDE is a term commonly used in the programming world to describe the interface and environment
that we use to create our applications. It is called integrated because we can access virtually all of the
development tools that we need from one screen called an interface. The IDE is also commonly referred to as
the design environment, or the program.
Tha Visual Basic IDE is made up of a number of components
 Menu Bar
 Tool Bar
 Project Explorer
 Properties window
 Form Layout Window
 Toolbox
 Form Designer
 Object Browser

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 After click on the Standard EXE from the New Project screen the opening screen will be displayed.

Title bar:
 The title is displayed on the title bar. [“Project1-Microsoft Visual Basic [design]”].
The titlebar in Visual Basic is the header area at the top of the form which displays your application - it
commonly displays an icon, followed by the name of the software currently running (visual Basic,
Microsoft Word, etc) and at the furthermost right hand side it will contain the minimize, maximize, exit
icons.

Menu Bar:
This Menu Bar displays the commands that are required to build an application. The main menu items have
sub menu items that can be chosen when needed. The toolbars in the menu bar provide quick access to the
commonly used commands and a button in the toolbar is clicked once to carry out the action represented by it.

Toolbox:
2

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

The Toolbox contains a set of controls that are used to place on a Form at design time thereby creating the
user interface area. Additional controls can be included in the toolbox by using the Components menu item on
the Project menu.
A Toolbox is represented in figure 2 shown below.

Toolbox window with its controls available commonly.

Control Description
Pointer Provides a way to move and resize the controls form
Displays icons/bitmaps and metafiles. It displays text or acts as a visual container for
PictureBox
other controls.
TextBox Used to display message and enter text.
Frame Serves as a visual and functional container for controls
CommandButton Used to carry out the specified action when the user chooses it.
CheckBox Displays a True/False or Yes/No option.
OptionButton control which is a part of an option group allows the user to select only
OptionButton
one option even it displays mulitiple choices.
ListBox Displays a list of items from which a user can select one.
Contains a TextBox and a ListBox. This allows the user to select an ietm from the
ComboBox
dropdown ListBox, or to type in a selection in the TextBox.
HScrollBar and
These controls allow the user to select a value within the specified range of values
VScrollBar
Timer Executes the timer events at specified intervals of time
DriveListBox Displays the valid disk drives and allows the user to select one of them.
DirListBox Allows the user to select the directories and paths, which are displayed.
FileListBox Displays a set of files from which a user can select the desired one.
Shape Used to add shape (rectangle, square or circle) to a Form
Line Used to draw straight line to the Form
used to display images such as icons, bitmaps and metafiles. But less capability than
Image
the PictureBox
Data Enables the use to connect to an existing database and display information from it.
OLE Used to link or embed an object, display and manipulate data from other windows
3

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

based applications.
Label Displays a text that the user cannot modify or interact with.

Project Explorer
 Docked on the right side of the screen, just under the tollbar, is the Project Explorer window. The
Project Explorer as shown in in figure servres as a quick reference to the various elements of a project
namely form, classes and modules. All of the object that make up the application are packed in a project.
A simple project will typically contain one form, which is a window that is designed as part of a
program's interface. It is possible to develop any number of forms for use in a program, although a
program may consist of a single form. In addition to forms, the Project Explorer window also lists code
modules and classes.

Figure 3 Project Explorer

Properties Window:
The Properties Window exposes the various characteristics of selected objects. Each and every form in
an application is considered an object. Now, each object in Visual Basic has characteristics such as color and
size. Other characteristics affect not just the appearance of the object but the way it behaves too. All these
characteristics of an object are called its properties. Thus, a form has properties and any controls placed on it
will have propeties too. All of these properties are displayed in the Properties Window.

Form Layout Window:


 This window allows you to position the forms in your application.

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Menu Bar:

This Menu Bar displays the commands that are required to build an application. The main menu items
have sub menu items that can be chosen when needed. The toolbars in the menu bar provide quick access to the
commonly used commands and a button in the toolbar is clicked once to carry out the action represented by it.

File Contains options for opening projects, closing projects, printing projects, etc.

Edit Contains options such as cut, paste, find, undo, delete, etc.

View Contains options for displaying IDE windows and tool bars.

Project Contains options for adding features such as forms to the project.

Format Contains options for aligning and locking a form’s controls.

Debug Contains options for debugging.

Run Contains options for executing a program, stopping a program, etc.

Query Contains options for manipulating data retrieved from a database.

Diagram Contains options for editing and viewing the design of databases.

Tools Contains options for IDE tools and options for customizing the environment.

Add-Ins Contains options for using, installing and removing add-ins. Add-ins are typically
independent software vendor (ISV) products that extend Visual Basic’s features

. Windows Contains options for arranging and displaying windows.

Help Contains options for getting help.

Toolbars:
The toolbar in the menu bar provide quick access to the commonly used commands.
Standard toolbar:
The standard toolbar contains buttons that are shortcut to some commonly used items.Some of them are
open Project, Save project, cut, copy and paste.

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Edit Toolbar:
Contains buttons that are shortcuts to some commonly used menu items.
Frequently used when editing code.

Debug Toolbar
Debugging code is essential to producing a successful Visual Basic application. One of the most useful Visual
Basic toolbars helps identify and correct coding errors. The Debug toolbar allows programmers to click buttons
and navigate through code as it executes.

Form Editor Toolbar

Contains buttons that are shortcuts to some commonly used menu items. Frequently
used when aligning and selecting the objects.

Object Browser
The Object Browser allows us to browse through the various properties, events and methods that are
made available to us. It is accessed by selecting Object Browser from the View menu or pressing the key F2.
The left column of the Object Browser lists the objects and classes that are available in the projects that are
opened and the controls that have been referenced in them. It is possible for us to scroll through the list and

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

select the object or class that we wish to inspect. After an object is picked up from the Classes list, we can see
its members (properties, methods and events) in the right column.
A property is represented by a small icon that has a hand holding a piece of paper. Methods are denoted by little
green blocks, while events are denoted by yellow lightning bolt icon.
Object naming conversions of controls (prefix)
Form -frm
Label-lbl
TextBox-txt
CommandButton-cmd
CheckBox -chk
OptionButton -opt
ComboBox -cbo
ListBox-lst
Frame-fme
PictureBox -pic
Image-img
Shape-shp
Line -lin
HScrollBar -hsb
VScrollBar –vsb
Single document interface (SDI)

Visual basic support the following three environments such as –


 Single document interface (SDI)
 Multiple document interface (MDI)
 Internet explorer interface.

SDI:
A single documents interface or SDI contains single data window. An example, of the SDI interface in
the WordPad application included with Microsoft windows. In WordPad, we can only one document at a time.
We must close one document in order to open another.
A SDI application usually doesn’t contain window menus on its menu bar because we can’t move between data
windows. When user opens new data file, the data replace the data currently shown in the open window.
MDI:
MDI stands for Multiple Document Interface, a Graphic User Interface which is able to show multiple
documents can be showed at one time is known as MDI. The most feasible example of MDI can be
several latest applications which include all the latest web browsers and applications such as Facebook
and twitter. There is also another difference which comes in the form of grouping which exists
whenever an MDI is used but this option is not available in SDI and can only be achieved with the help
of command window.

To switch between SDI and MDI modes:

1. Select Options from the Tools menu.


The Options dialog box is displayed.
2. Select the Advanced tab .
3. Check or uncheck the SDI Development Environment check box.
Visual Basic then informs you that change will take place from next invocation of Visual Basic.
4. Close Visual Basic IDE and restart it to get it in the mode you want.

Note: You can also run Visual Basic from command line using /sdi or /mdi parameter to put IDE in the
selected mode.
Toolbox:

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

The toolbox is a floating window that allows you to add controls to a userform.
It is not possible to add controls using menu commands.
When a userform is activated the Toolbox is displayed automatically in a floating window.
To add a control, click on the corresponding icon on the toolbox and drag it onto the userform.

Select Objects - Select Objects is the only item in the Toolbox that doesn't draw a control. When you select it,
you can only resize or move a control that has already been drawn on a form.

CUSTOM CONTROLS AND COMPONENTS:

The toolbox is located at the left of the screen.


To add new components to the toolbox,follow these steps

1.choose Project/Components.

2.from the dialog box,that pops up.

3.click on ok.

we can add multiple tabs to the toolbox in order to make it easier to see what components you have
available.To add another tab,do this:

1.Right click in the toolbar.


2.choose Add tab from the context menu that pops up
3.Give the new tab a name.
To actually add the controls,we can either
 Drag the controls from an existing tab, or
 Click on the tab in order to make it active,and then add the new component via the components
dialog box.

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

THE INITIAL FORM WINDOW:-

The intial form window takes up a part of the center of the screen.To customize the form window by
adding controls and changing the size,the result is the intial form window.

THE PROPERTIES WINDOW:


It is located above the Form Layout window on the right-hand side of the VB environment. If the
properties window is hidden make it visible by pressing F4, or choose View|Properties.The title bar of the
properties window indicates the properties of control. The line below the title bar indicates what object the user
working with.It consists of two columns. The first column indicates the properties. The second column
indicates the current setting of the property. It is also called as settings box.The right-hand column is working
like an ordinary text box, the method for changing the setting for a property by
i. Move the mouse until the mouse pointer is in the right column of the correct line in the properties
window.
ii. Click at the location where the text to be inserted.
iii. Enter the text.
The properties window consists of two Tabs. The first default Tab is alphabetical. The properties to be
listed by functionality by using the second Tab categorized at the top of the properties window.

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Moving Through the Properties Window:


To quickly move through the properties in the properties window use Shift+CTRL+letter key. This
moves to the first property that begins with that letter. Subsequent uses of this combination move to succeeding
properties that begin with that letter. (OR) Use the arrow keys or the mouse to scroll through the properties
window.
Example:
Whenever a property has a fixed number of options the arrow in the line of the properties window indicates
that a drop-down list box is available.The MaxButton property consists of two values. The default value is
True. To change this property to False by using three ways:
i. Once we have highlighted this line in the properties window, the simplest way to do this is just to press
F. the MaxButton property changes from True to False.
ii. Double-click in the right-hand column.
iii. To click the arrow immediately to the right of the settings box where True appears. To select the False
option by pressing DOWN ARROW and then pressing ENTER, or by clicking the word False.
The three ways are available to run a Visual Basic application:
i. Select the Start option from the toolbar by clicking the forward arrow.

10

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

ii. Select the Start option from Run menu by using the mouse or by pressing ALT+R, S.
iii. Press F5.
After a short delay, the form will pop-up super-imposed on the Visual Basic IDE and looking like as follows:

To return to developing an application click on the exit(x) button on the form, or open the Run menu and click
the End option, or use the End tool.
1.2.2 Working with the Properties Window:
i. Display the properties window by pressing F4 if it is not visible.
ii. Move to the properties window and select an item from the properties in the list box.
iii. Enter the new setting for the property.
iv. Press ENTER to accept new string.
Keyboard Shortcuts:
The following keyboard shortcuts used for manipulating the properties window:
Key Action
SHIFT+CTRL+letter key Moves to the first item beginning with that letter.
DOWN ARROW Moves to the next item in the properties list box.
UP ARROW Moves to the previous item in the properties list box.
PAGE DOWN/END Moves to the last item displayed in the properties list box or to the last item.
PAGE UP/HOME Moves to the first item displayed in the properties list box or to the first
item.
F4 Brings up the properties window.
COMMON FORM PROPERTIES
The Form consists of many properties. Some of the commonly used properties are:
 Caption
 Name
 Appearance
11

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 BorderStyle
 ControlBox
 Enabled
 Font
 Height, Width
 Icon
 Left, Top
 MousePointer, MouseIcon
 StartUpPosition
 Visible
 WindowState
Caption:
This property sets the title of the form. It can be changed at runtime. It must be meaningful and
informative to the user.
Name:
It is used only in code. It gives the name by which the Form is referred to in the user code. The name of
a form cannot be changed at runtime.
Appearance:
This property determines whether the form will have a three-dimensional look. The default value of 1
indicates the form will appear three-dimensional. If it changes to 0, the form will appear flat.
BorderStyle:
This property determines the type of window that the user will view at runtime. It consists of five values.
The default value, 2-Sizable, allows the user to size and shape the form via the hot spots located on the
boundary of the form.
The other values are:
 1-Fixed Single
 3-Fixed Double
 4-Fixed ToolWindow
 5-Sizable ToolWindow
 0-None
i. Set the Borderstyle value to 0-None, the application does not consists of no border. The form created
without a border cannot be moved, resized, or reshaped.
ii. The value 1-FixedSingle, the user no longer be able to resize the window. The users minimize and
maximize the form window.
iii. The third setting 3-FixedDouble not used for ordinary forms, but it is commonly used for dialog
boxes. It gives a nonsizable (it has no hot spots).

12

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

iv. The 4-Fixed ToolWindow setting not used very often. Under windows 95/98, this displays the form
with a close button. The fifth setting 5-Sizable ToolWindow like an FixedToolWindow setting.

ControlBox:
The value of this property is True or False. If it is set to True, the Control Box is visible on the top left-
hand corner of the form. The minimize and maximize button are displayed on the title bar of the Form. The
value of this property is set to False the user not access the minimize and maximize commands.
Enabled:
This property consists of two values. The default value is True. If it is set to False, the form cannot
respond to any events such as the user clicking on the form.
Font:
To access the Font property press Ctrl+Shift+F. It includes the following:
 Font Name: Name of the font.
 Font Bold: If set to true, the text will be displayed in bold.
 Font Size: Set the size of the text in points.

Height, Width:
This property indicates the height and width of the form. The user can change their values directly via the
properties window.To perform this users enter the value in the appropriate line in the right-hand column of the
properties window.

13

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Icon:
This property determines the icon of the user application will display when it is minimized on the
toolbar. To choose an icon for user applications go to properties window and select the Icon property. Click the
box containing three dots a dialog box will appear.

From this dialog box we can choose the icon for the application
Left, Top:
These properties determine the distance between the left or top of the form and the screen. To control
these properties by using the Form Layout window.
MousePointer, MouseIcon:
The MousePointer is a useful property it set the shape of the mouse pointer. The default value is 0, but
as the pull-down list indicates, there are 17 other values. Set the MosuePointer property to a value of 99, the
user able to use a custom icon.
StartUpPosition:
It is another way to decide on the initial position of the form at run time. It is more precise than using
the Form Layout window.
Visible:
AThis property consists of two values. The default value is True. Set the value of this property to False, the
form will no longer be visible.

WindowState:
This property determines how the form will look at run time. There are three possible settings. A setting
of 1 reduces the form to an icon, and a setting of 2 maximizes the form. A setting of 0 is the normal default
setting.

14

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

SCALE PROPERTIES
The scale properties are need to position objects or text in a form accurately. The following properties
that affect the scale used in a form:
 ScaleMode
 ScaleHeight, ScaleWidth
 ScaleLeft, ScaleTop
ScaleMode:
It is used to change the units used in the forms internal coordinate system. It consists of seven
possibilities. The default value is 1.
ScaleHeight, ScaleWidth:
Using this property we can set the own scale for the height and width of the form.
ScaleLeft, ScaleTop:
These properties describe what value visual basic uses for the left or top corner of the form. The original
(default) value for each of these properties is 0. These properties are most useful when the user working with
graphics like ScaleHeight and ScaleWidth.
1.5 COLOR PROPERTIES
Using Color properties specify the background color (BackColor) and the foreground color (Forecolor)
for text and graphics in the form.
1.5.1 The BackColor and ForeColor Properties via the Color Palette:
To set the Backcolor property, open the properties window and select BackColor (represented by
hexadecimal code-base 16). To set colors is to choose one of the color properties and click the down arrow in
the Settings box. This opens up a tabbed dialog box with two tabs.

15

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

The System tab on this dialog box gives the colors currently used by windows for its various elements.
To click on the Palette tab, the color grid will appear. Select any color from the Palette and the Color code for
that color is placed in the settings box. The background color of the form will automatically show the user
changes to the BackGround property.

A.Working with the Color Palette:


To create the own colors by working with the color palette directly. Open the color palette by view
menu choosing the color palette. (ALT+V, L).

To the left of the palette, a dark box enclosed in a lighter box. The inner box displays the current
foreground color, and the outer box displays the current background color.To change the foreground color by
clicking the inner box and the clicking any of the colored boxes displayed.To change the background color,
click the outer box and then click any of the colored boxes displayed.To go back to the default colors specified
in the Windows control panel, click the Default command button at the right.
To create own colors for the color palette consists of the following steps:
 Click one of these blank boxes, and then click the Define Colors command button.
This opens the Define Color dialog box.
 Change the amount of color to suit the user needs by adjusting the controls in the dialog box.
 Press the Add Color button to create the custom color or the Close button to cancel.

16

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

ALTERING A FORM
How Can We Resize Or Altering A Form At Design And Run Time? (5 Marks)
Altering a Form:
 One way to resize a form is common to all Microsoft windows
applications: Move the mouse to one of the hot spots of the form.
The hot spots are the sides or corners of the form. The mouse
pointer changes to a double-headed arrow when you’re at a hot
spot. At this point you can hold the mouse button down and drag
the form to change its size or shape.
 To change the position of the form at run time, follow these steps:
 Move the cursor to the Form Layout window. (The cursor
will change to a four-headed arrow).
 Drag the form to the position in which you want it appear
when the user starts your program.
 The changes in the Form Layout window are run-time changes only. The position of the form in the
design window in the center of your screen doesn’t reflect the user changes.

THE PROPERTIES WINDOWS


Discuss About The Properties Window. (5 Marks)
17

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

How Can We Work With The Properties Window? (2 Marks)


List out The Keyboard Shortcuts For Manipulating The Properties Window (2 Marks & 5 Marks)
 It is located above the Form Layout window on the right-hand side of the VB environment. If the
properties window is hidden make it visible by pressing F4, or choose View|Properties.
 The title bar of the properties window indicates the properties of control. The line below the title bar
indicates what object the user working with.
 It consists of two columns. The first column indicates the properties. The second column indicates the
current setting of the property. It is also called as settings box.
 The right-hand column is working like an ordinary text box, the method for changing the setting for a
property by
 Move the mouse until the mouse pointer is in the right column of the correct line in the
properties window.
 Click at the location where the text to be inserted.
 Enter the text.
 The properties window consists of two Tabs. The first default Tab is alphabetical. The properties to be
listed by functionality by using the second Tab categorized at the top of the properties window.

Moving Through the Properties Window:


 To quickly move through the properties in the properties window use Shift+CTRL+letter key. This
moves to the first property that begins with that letter. Subsequent uses of this combination move to
succeeding properties that begin with that letter. (OR) Use the arrow keys or the mouse to scroll through
the properties window.
Example:
 Whenever a property has a fixed number of options the arrow in the line of the properties window
indicates that a drop-down list box is available.
 The MaxButton property consists of two values. The default value is True. To change this property to
False by using three ways:
 Once you have highlighted this line in the properties window, the simplest way to do this
is just to press F. the MaxButton property changes from True to False.
 Double-click in the right-hand column.
 To click the arrow immediately to the right of the settings box where True appears. To
select the False option by pressing DOWN ARROW and then pressing ENTER, or by
clicking the word False.

Summary Working with the Properties Window:


 Display the properties window by pressing F4 if it is not visible.
 Move to the properties window and select an item from the properties in the list box.
 Enter the new setting for the property.
 Press ENTER to accept new string.
Keyboard Shortcuts:
18

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 The following keyboard shortcuts used for manipulating the properties window:

Key Action
SHIFT+CTRL+letter key Moves to the first item beginning with that letter.
DOWN ARROW Moves to the next item in the properties list box.
UP ARROW Moves to the previous item in the properties list box.
PAGE DOWN/END Moves to the last item displayed in the properties list box or to the last item.
PAGE UP/HOME Moves to the first item displayed in the properties list box or to the first item.
F4 Brings up the properties window.

How Can We Run and Exit from a VB Application. (2 Marks)


 The three ways are available to run a Visual
Basic application:
 Select the Start option from the
toolbar by clicking the forward
arrow.
 Select the Start option from Run
menu by using the mouse or by
pressing ALT+R, S.
 Press F5.
 After a short delay, the form will pop-up
super-imposed on the Visual Basic IDE and
looking like as displayed:
 To return to developing an application click
on the exit(x) button on the form, or open the
Run menu and click the End option, or use
the End tool.
COMMON FORM PROPERTY
Explain About The Form Properties. (2 Marks & 5 Marks)
 The Form consists of many properties. Some of the commonly used properties are:
 Caption
 Name
 Appearance
 BorderStyle
 ControlBox
 Enabled
 Font
 Height, Width
 Icon
 Left, Top
 MousePointer, MouseIcon
 StartUpPosition
 Visible
 WindowState
Caption:
 This property sets the title of the form. It can be changed at runtime. It must be meaningful and
informative to the user.

Name:
 It is used only in code. It gives the name by which the Form is referred to in your code. The name of a
form cannot be changed at runtime.
Appearance:
19

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 This property determines whether the form will have a three-dimensional look. The default value of 1
indicates the form will appear three-dimensional. If it changes to 0, the form will appear flat.
BorderStyle:
 This property determines the type of window that the user will view at runtime. It consists of five
values. The default value, 2-Sizable, allows the user to size and shape the form via the hot spots located
on the boundary of the form.
 The other values are:
 1-Fixed Single
 3-Fixed Double
 4-Fixed ToolWindow
 5-Sizable ToolWindow
 0-None
 Set the Borderstyle value to 0-None, the application does not consists of no border. The form created
without a border cannot be moved, resized, or reshaped.
 The value 1-FixedSingle, the user no longer is able to resize the window. The users minimize and
maximize the form window.
 The third setting 3-FixedDouble not used for ordinary forms, but it is commonly used for dialog boxes.
It gives a nonsizable (it has no hot spots).
 The 4-Fixed ToolWindow setting not used very often. Under windows 95/98, this displays the form
with a close button. The fifth setting 5-Sizable ToolWindow like a FixedToolWindow setting.
ControlBox:
 The value of this property is true or False. If it is set to True, the Control Box is visible on the top left-
hand corner of the form. The minimize and maximize button are displayed on the title bar of the Form.
The value of this property is set to False the user not access the minimize and maximize commands.
Enabled:
 This property consists of two values. The default value is True. If it is set to False, the form cannot
respond to any events such as the user clicking on the form.
Font:
 To access the Font property press Ctrl+Shift+F. It includes the following:
 Font Name: Name of the font.
 Font Bold: If set to true, the text will be displayed in bold.
 Font Size: Set the size of the text in points.
Height, Width:
 This property indicates the height and width of the form. The user can change their values directly via
the properties window.
 To perform this users enter the value in the appropriate line in the right-hand column of the properties
window.
Icon:
 This property determines the icon your application will
display when it is minimized on the toolbar. To choose an
icon for user applications go to properties window and
select the Icon property. Click the box containing three dots
a dialog box will appear.
 From this adjacent dialog box we can choose the icon for
the application
Left, Top:
 These properties determine the distance between the left or
top of the form and the screen. To control these properties by using the Form Layout window.
MousePointer, MouseIcon:
 The MousePointer is a useful property it set the shape of the mouse pointer. The default value is 0, but
as the pull-down list indicates, there are 17 other values. Set the MosuePointer property to a value of 99,
the user able to use a custom icon.

StartUpPosition:

20

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 It is another way to decide on the initial position of the form at run time. It is more precise than using
the Form Layout window.
Visible:
 This property consists of two values. The default value is True. Set the value of this property to False,
the form will no longer be visible.
WindowState:
 This property determines how the form will look at run time. There are three possible settings. A setting
of 1 reduces the form to an icon, and a setting of 2 maximizes the form. A setting of 0 is the normal
default setting.
SCALE PROPERTIES
List Out And Explain About The Scale Properties. (5 Marks)
 The scale properties are need to position objects or text in a form accurately. The following properties
that affect the scale used in a form:
 ScaleMode
 ScaleHeight, ScaleWidth
 ScaleLeft, ScaleTop
ScaleMode:
 It allows you to change the units used in the forms internal coordinate system. It consists of seven
possibilities. The default value is 1.
ScaleHeight,ScaleWidth:
 Use this property when you set up your own scale for the height and width of the form.
ScaleLeft,ScaleTop:
 These properties describe what value visual basic uses for the left or top corner of the form. The original
(default) value for each of these properties is 0.
 These properties are most useful when you are working with graphics like ScaleHeight and ScaleWidth.
COLOR PROPERTIES
Write Short Notes On Color Properties. (5 Marks)
How Can We Work With Color Palette? (2 Marks)
 Using Color properties specify the background color (BackColor) and the foreground color (Forecolor)
for text and graphics in the form.
The BackColor and ForeColor Properties via the Color Palette:
 To set the Backcolor property, open the properties window and select BackColor (represented by
hexadecimal code-base 16). To set colors is to choose one of the color properties and click the down
arrow in the Settings box. This opens up a tabbed dialog box with two tabs.

 The System tab on this dialog box gives the colors currently used by windows for its various elements.
To click on the Palette tab, the color grid will appear. Select any color from the Palette and the Color
code for that color is placed in the settings box. The background color of the form will automatically
show the user changes to the BackGround property.

21

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Working with the Color Palette:


 To create the own colors by working with the color palette directly. Open the color palette by view
menu choosing the color palette. (ALT+V, L).

 To the left of the palette, a dark box enclosed in a lighter box. The inner box displays the current
foreground color, and the outer box displays the current background color.
 To change the foreground color by clicking the inner box and the clicking any of the colored boxes
displayed.
 To change the background color, click the outer box and then click any of
the colored boxes displayed.
 To go back to the default colors specified in the Windows control
panel, click the Default command button at the right.
 To create own colors for the color palette consists of the following
steps:
 Click one of these blank boxes, and then click the Define
Colors command button. This opens the Define Color
dialog box.
 Change the amount of color to suit the user needs by
adjusting the controls in the dialog box.
 Press the Add Color button to create the custom color or the
Close button to cancel.

MAKING A FORM RESPONSIVE


Discuss About Code Window. (5 Marks)
How Can We Write A Simple Event Procedure? (5 Marks)
How Can We Open The Code Window? (2 Marks)
 The Visual Basic objects can recognize many different events. Each objects associated with any event in
the VB environment.
 The user writes the event procedure that is lines of programming code that tell visual basic how to
respond to a given event.
Opening the Code Window:
 Double-Click on the form.
 Pressing the right mouse button on the control. Choose the “View Code” option.
 Press F7 after clicking on the control.
 Click on View in the menu bar. Then click Code.
The Code Window and Writing a Simple Event Procedure:
 Double-click in any blank part of Form1 the screen will appear as follows: The code window consists of
two drop-down list boxes in the top part of the screen. The right-hand side combo box lists all the events
a form can recognize. The left-hand box in the code window, list all the controls used in the form.

22

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Event Procedure Template:


 The below code is an example of event procedure template.
Private Sub Form_Load()

End Sub
 Private means that the variables declared and the code used only by this function. The Form_Load() is
the name of the function. End Sub means end of this sub-routine.
 The above Form_Load event is triggered when Visual Basic loads a form in memory.
Private Sub Form_Load()
BackColor=vbRed
End Sub
the above code changes the background color to red after run the program.
Working with the Form_Click Event:
 To display the Form_Click procedure in the code window by using the following steps:
o Move to the event drop-down list box on the right and click the down arrow.
o Move through the box until the user get to the click item. To quickly go to a specific event
procedure by pressing the first letter of the item.
Example: Pressing C will quickly take you to the click procedure.
o Click on it.
 After complete the above steps the VB does the following:
o Gives the new event procedure template for the Form_Click event procedure.
o Adds a dotted line between the Form_Load event and the Click event.
o Moves the cursor to the blank line before the End Sub line in the Click event procedure
template.
o Press the TAB key once or the SPACEBAR a few times and type print “You Clicked the
mouse once.”
o Now press F5 to run the application. The print command sends the exact text found between
the quotation marks directly to the form.

23

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

More General Event Procedure:


 The code for an event procedure for a form in VB begins with the following:
o Private Sub Form_NameOfTheEvent()
Example:
Event Procedure Tells the Form
Private Sub Form_Click() To respond to a Click
Private Sub Form_DblClick() To respond to a double_click
Private Sub Form_Resize() To respond when the user resizes the form
Monitoring Multiple Events:
 To add the new template Double-click event to your code window and type Print “I said to click once,
not twice!”
Private Sub Form_DblClick()
Print “I said to click once, not twice!”
End Sub
 Now run the application and double click the form it displays both the lines of text appear on the screen.
If you want to clear the screen before displaying the second message use the Cls keyword.
Private Sub Form_DblClick()
Cls
Print “I said to click once, not twice!”
End Sub
 The another syntax for the Print or Cls method, which is used for other Visual Basic objects. The
general form is usually described as Object.Method.
Example:
Form1.Cls
Form1.print “JaiRam College”

PRINTING A VISUAL REPRESENTATION OF A FORM


How Can We Print The Visual Representation Of A Form? (2 Marks)
 Getting an image of the form, including whatever is currently displayed on the form, to the printer
requires only a single command: PrintForm
 The PrintForm method tries to send to your printer a dot-for-dot image of the entire form.
Example: Add this line PrintForm to the Double-click procedure before the End Sub line.
TYPeS
Explain About Types. (5 Marks)
 Nobody types completely accurately all the time. VB can point out many typing errors when you enter a
line of code, and it will even correct some. All this happens even before you try to run your program.
 But few programmers enter code without typos. Suppose
you made a typo when you were writing the event
procedure with the misspelled the command word Print by
typing printf instead.
Example:
Private Sub Form_Click()
Printf “You clicked the mouse once”
End Sub
 The word Printf should be in a different color than it was
when it was correctly spelled. If the user does not notice the
color change and try to run the program and click in the
form, VB will immediately respond with an error message
box.

 If the user press ENTER or click the OK command button, the offending word remains highlighted, and
the user either type the correct replacement or move the mouse pointer to the “f” and press DEL. After
you made the correction and run the program again.

24

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 Visual basic can find some syntax errors after you finish typing a line. To make sure this feature is on,
choose Tools|Options and then go to the Environment page. Move to the item marked Auto Syntax
Check and make sure that it is checked (on).
CREATING STAND-ALONE WINDOWS PROGRAM
How Can We Create The Stand-Alone Windows Programs? (2 Marks)
 One of the most exciting features of Visual Basic is the ability
to change your projects into stand-alone Microsoft
windows programs.
 To make a stand-alone VB application, simply go to the File
menu and choose the Make Project EXE File option (ALT+F,
K). This opens a dialog box like as follows:
 The default name for the .exe version of your file is the project
name. For the stand-alone program, the Windows desktop uses
the same icon that Visual Basic uses for the executable version
of the Project.

THE TOOLBOX
Discuss About Toolbox. (5 Marks)
 The toolbox contains set of tools. It itself contains the icons
representing the controls you can add to your forms.
 The standard edition of Visual Basic comes with more than 20
different controls; the professional and Enterprise editions add
many controls.
 It is located on the left of the VB screen, but it need not be visible at
all times. If the toolbox is not visible, make it visible in order to
work with a control. To open the toolbox, use the Toolbox tool or
go to the view menu and choose Toolbox (ALT+V,X).
The Pointer:
 The first item on the toolbox is not a control but is used to manipulate controls after you create them.
Click the pointer when you want to select, resize, or move an existing control. The Pointer is
automatically activated after you place a control on a form.
Command Buttons:
 It is also called as push buttons. The user will click on this button and the computer will perform the
task associated with the button.
Image Controls:
 It is used to display the pictures. It uses the fewest Windows resources for displaying images. The
command button also used to display the picture.
Picture Box:
 It can display a graphic from a bitmap, icon, or metafile, JPEG, GIF files.
Text Boxes:
 It is used to display text or to accept user input. It is sometimes called as edit fields. It can wordwrap
automatically or display multiple lines of text.
 All the ordinary windows editing tools, such as cutting and pasting, are available when you enter
information in a text box. This means users can automatically use such shortcuts as CTRL+X to cut,
CTRL+C to copy, and CTRL+V to paste. The usual limit for a text box is approximately 32,000
characters.
Labels:
 Use labels for information that users shouldn’t be able to change. It is used to identify objects. It
responds to 12 events, usually they are used passively-for display purposes only.

CREATING CONTROLS
25

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

How Can We Create Controls On A Form? (5 Marks)


How Can We Resize And Move The Existing Control? (2 Marks)
How Can We Work With Multiple Controls? (5 Marks)
How Can We Lock and Delete The Controls? (2 Marks)
 To get a control on a form by double clicking on its icon in the toolbox. This gives the control in its
default size and shape in the middle of the form.
 Many of the more sophisticated methods for using the toolbox and similar to those used in a paint
program. To use a combination of pointing, clicking and dragging to manipulate the toolbox.
 To draw an item from the toolbox on a form at a specific location with a specific size:
 Move the mouse pointer to the tool you want to use and click.
 Move the mouse pointer to the form.
 Hold the mouse button down and drag the mouse to create the object, and release the
button. [Now the controls has eight little boxes, called sizing handles]
Use these handles to move and resize a control after the control has been created.

Working with a Control Already on a Form:


 To work with existing control first select the control and then resize and move the control.
Resizing an Existing Control:
 To change the size of an existing command button at design time:
o Use the Properties window to adjust the Width and
Height properties.
o Work with the sizing handles. When the handles are
visible the control is selected.
 To resizing a control with the sizing handles by following
these steps:
o Move the mouse pointer to a sizing handle and
click and hold down the left mouse button.
o Drag the mouse until the control is the size you
want.
Moving an Existing Control:
 To move an existing control with the mouse, the focus must be at that control.
Steps:
 Move the pointer anywhere inside the control, click the left mouse button, and hold it down.
 Drag the mouse until the control is at the location you want it to be, and then release the left button.
 For finer control over the movement of controls:
 Select the control
 Use CTRL+ an arrow key to move the control one grid mark at a time.
 Directly adjust the Left and Top properties in the Properties window.

Using the Double-Click shortcut for Creating Controls:


 The user double-click on any of the toolbox icons, the matching control appears in the center of the
screen.

Example:
 To create an application with five command buttons symmetrically, double-click on the Command
Button icon five times. This stacks five command buttons in the center of the form.
 Now we can move the buttons to the particular location. Change the captions by adjusting the Caption
property of the command buttons via the Properties window.

Working with Multiple Controls:


 To work with multiple controls as a single unit, use the “dragging” method to select multiple controls.

26

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Steps:
 Imagine a rectangle that surrounds only those controls you want to select. Move to one
corner of this imagined rectangle and click the left mouse button.
 Hold the left mouse button down and drag the dotted rectangle until it covers all the
controls you want to select. Then release the mouse button. The grouped control now
contains sizing handles.
 Once the user selected a group of controls, when you move any control in the group VB menus the other
controls in a similar way.
 The next method is to select each control by moving the mouse pointer to it and holding down the left
mouse button while pressing CTRL.
 To take controls out of their temporary grouping and treat them individually again:
 Move the mouse pointer to any place outside the selected controls and click.
 The Tools|Format menu has multiple submenus that let you resize and reshape a group of controls. The
Format|Align submenu is used to align controls so that their left edges match, their centers are aligned,
and so on.

 The Format| Make Same Size menu is used to make a group of controls all the same width, height, or
both:

Locking Controls:
 Once the control is positioned on the form, the user want to lock the control by using Lock feature. By
choosing Format |Lock Controls or Lock Control tool from the toolbar, you want prevent yourself from
inadvertently moving a properly positioned control. This item is a toggle, choosing it again frees up
controls we can move them again.
Deleting Controls:
 To delete the control by using the following steps:
 Move the mouse pointer until it is inside the control, and click the left mouse button to
select it.
 Press DEL, or open the Edit menu and choose the Delete option by pressing ALT+E, D.
 To delete many controls at once, first select the controls as one unit and press DEL key or Delete menu
option.

Discuss About Name Property. (2 Marks & 5 Marks)

27

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

THE NAME (CONTROL NAME) PROPERTY


 This property determines the name by which it is referred to in the program. This property is more
important the user avoid this name use Me keyword in your code because VB knows the form that the
code is attached to.
Example: Height = 5000 or Me.Height = 5000
 To change the height of a command button whose Name property is MyCommandButton, represented
as
 MyCommandButton.Height=500
 To Double-Click the MyCommandButton the event procedure will look as follows:
Private Sub MyCommandButton_Click()
End Sub
 The limits on a control name are the same as for form names:
 The name must begin with a letter.
 Use any combination of letters, digits, and underscores.
 It cannot be longer than 40 characters.
Explain About The Properties Of Command Button. (5 Marks)
PROPERTIES OF COMMAND BUTTONS
 The properties window is used to customize the controls.
The Caption Property:
 The caption property on a command button determines what the user sees on the face of the button. The
user use any text for the caption on a command button is automatically centered within the button.
 It always start with captions like Command1, Command2, reflecting the default value of the Name
property. The number indicates the order in which the buttons were created.
 The name in the button will not fit inside the default size of a command button, create the Caption for
the button first via the properties window and then resize the control to fit it.
 To change the caption property by
 Move to the Properties window.
 Go to the Caption property by using the mouse or the UP ARROW and DOWN ARROW
keys. (SHIFT+CTRL+C for fast access).
 Type the new setting for the Caption property.
Other Useful Properties for Command Buttons:
 The command button contains 31 properties.
Visible:
 This property determines whether the command button is visible or not. This property can only be set to
True or False.
Enabled:
 This property determines whether the button can respond to any event. If you set this property to False,
VB will not respond to any event concerning that button.
 It is more of ten temporarily toggled on or off via code than set in the Properties window.
Font:
 This property controls which font is used for the caption of the button. Use only one font at a time.
When you open up the Font dialog box, all the font characteristics-Bold, Italic, Font Name, and so on-
can be set independently for each command button.
Height, Width:
 These properties define the height and width of the command button. To change the settings for these
properties directly from the Properties window or by using the sizing handles.
Left, Top:
 These properties determine the distance between the command button and the left edge and top of the
container respectively.
MousePointer:
 Setting the MosuePointer to something different than the usual arrow is a good way to give a user
feedback that the user has moved the focus to the command button.
DisabledPicture, DownPicture, Picture, Style:
 VB gives command buttons the ability to display graphics. The standard picture types are bitmaps,
icons, jpegs, gifs, etc.,
28

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 To make a command button display a picture first, to set the Style property to 1. After that, you need
only specify the picture to be used as the value of the other three properties.
Shortcuts for Setting Properties:
 To set the Caption property for all the command buttons on your form. Se the caption for first command
button and immediately select another command, the Caption property for the new control is highlighted
in the properties window.
 To select a group of controls, the Properties window will show only the common properties that the
controls in the group share. Change one of them and all of them change.
Discuss About The Event Procedure Of Command Button. (5 Marks & 10 Marks)
Write Down The Format For An Event Procedure Template. (2 Marks)
Who Do You Make A Command Button As Escape Button? (5 Marks)
SIMPLE EVENT PROCEDURES FOR COMMAND BUTTON
 Writing an event procedure for a Command button is similar to writing one for a form. The VB opens
the code by either double-clicks a control or press F7 for shortcut.
General Form for an Event Procedure Template:
Private Sub ControlName_EventName()

End Sub
Example:
 Consider the command button with the caption “Click here for help!” and the name property is
CmdHelp. Now the event procedure template look like as follows:
Private Sub CmdHelp_Click()

End Sub
 To add a simple Print statement to this above procedure and run the application by pressing F5.
Print “No Help is yet available. Sorry”.
 After that click command button the information printed to the form behind the control.

Other Events for Command Buttons:


 The command buttons can respond to 12 events. The useful events are: GotFocus abd LostFocus. The
GotFocus event will occurs when focus comes to an object. The LostFocus event will respond to users
moving the focus away form the object.
 The event procedure for the above events look like as follows:
Private Sub Command1_GotFocus()

End Sub
Private Sub Command2_LostFocus()

End Sub
Some Final Points on Command Buttons:
 One of the methods for activating a command button is common to all Windows applications: move the
focus by pressing TAB, and then press the SPACEBAR when the focus is where you want it to be. Both
clicking and using the Tab|SpaceBar combination tell VB to activate the Click event procedure if you
wrote one for that control.
 It is possible to create an escape button for a form a user can activate an escape command button by
pressing Esc on the keyboard. Use an escape button to allow users to cancel an action.
 To set the Cancel property to True, the user makes that button as escape button. Setting the Cancel
property to True for one button automatically sets it to False for all the other command buttons on the
form, use only one escape (cancel) button per form.
 Once the user set this property press Esc, VB will trigger the Click event procedure for this button,
regardless of where the focus is.

Write Short Note On Access Keys. (5 Marks)


ACCESS KEYS

29

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 Many Windows applications allow pressing ALT and one other key, the access key, to quickly activate
a control or a menu item. These access keys are underlined in the caption of the control or name of the
menu item.
 VB makes it easy to set up an access key for any object that has Caption property. When the user set the
caption, place and ampersand (&) in front of the letter you want to be the access key.
 When the application is running, the user can activate this button either by pressing the ALT+the
underlined character or by clicking on the button.
Discuss About Image Controls. (5 Marks)
IMAGE CONTROLS
 The Image Controls is used to hold pictures. It can be used to display icons or pictures created with a
program such as Microsoft Paintbrush. They can also hold Windows metafiles of Jpegs or Gifs. Jpeg
format is also the common format used by most digital cameras.
 This controls respond to the Click event, the user use the images to substitute for the command buttons.
 To load a picture into an image control by resetting the value of Picture property. If the user uses the
Picture property for the image control, this opens up a dialog box that lets you choose what image file to
load.
 To reset the Picture property directly by copying an image from a graphics program to the Windows
clipboard and then using Copy command on the Edit menu to paste the image in to the image control.
Properties of Image Controls:
 The BorderStyle property for an image control has only two possible settings: you can enter have no
border (setting=0) or a fixed single border (setting=1).
 The important property is stretch property. This determines whether the image control adjusts to fit the
picture, or the picture adjusts to fit the control. This property is set to True the picture resizes to fit the
control. The default value of False indicates the control resizes itself to fit the picture.
List Out And Discuss About The Properties Of Text Box. (10 Marks)
What Is The Use Of Text Box? (2 Marks)
TEXT BOXES
 The text boxes are the primary method for accepting input and displaying output in Visual Basic.
Standard Properties of Text Boxes:
 It consists of 50 properties. The standard properties are:
 Name
 Font
 Enabled
 Visible
 ForeColor and BackColor
Name:
 This property indicates the name of the text box is used only for the code. (The Microsoft’s Prefix for
the Name property of a text box is txt).
Font:
 To set the font properties via the Font dialog box available from the Properties window, but the user can
only use one font per text box.
Enabled:
 This property affects whether the textbox will respond to events. If the text box is displayed, the user
cannot enter text inside it. It also grayed.
 It consists of two settings. The default value is true.
Visible:
 This property consists of two values. The default value is True. If it is change to False the text box will
disappear.
ForeColor and BackColor:
 It ForeColor affects the color of the text that is displayed. The BackColor affects the rest of the text box.
Both of these can be set independently of the surrounding container.
 It is easiest to set them using the color palette from the Properties window.
Some Special Properties for Text Boxes:
Text:

30

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 The default value for this property is set to Text1, Text2 and so on. If you want a Text box to be empty
when the application starts, select the Text property and blank out the original setting.
Alignment:
 This property controls how text is displayed. The default value is 0, which indicates the text is left-
aligned. Use a value of 1 and text is right-aligned. Use a value of 2 and text is centered.
MultiLine:
 This property determines whether a text box can accept more than one line of text when the user runs
the application, and it is usually combined with resetting the value of the Scrollbars property.
 VB automatically word-wraps when a user types more than one line of information into a multiline text
box. The multiline text boxes are the usual method for displaying large amounts of text in Visual Basic.
The limit for a multiline text box is approximately 32,000 characters.
ScrollBars:
 This property determines whether a text box has horizontal or vertical scrollbars. Without scrollbars, it
becomes much harder for the user to move through the data contained in the text box, thus making
editing the information that much more difficult.
 The four possible settings for the ScrollBars property are:
Value Meaning
0 The default value is 0. The text box lacks both vertical and horizontal scrollbars.
1 The text box has horizontal scrollbars only.
2 The text box has vertical scrollbars only.
3 The text box has both horizontal and vertical scroll bars.
BorderStyle:
 There are only two possible settings for the BorderStyle property for a text box. The default value is 1,
which gives the single-width border, called a fixed single. If you change the value of this property to 0,
the border disappears.
MaxLength:
 This property determines the maximum number of characters the text box will accept. The default value
is 0. Any setting other than 0 will limit the user’s ability to enter data into that text box to that number of
characters.
PasswordChar:
 The asterisk (*) symbol used as a password character. This feature is combined with the MaxLength
property to add a password feature to your programs.
Locked:
 This True/False property prevents users from changing the contents of the text box. Users can scroll
highlight text, but won’t be able to change it.
Event Procedures for Text Boxes:
 The text boxes can recognize 23 events. VB monitors the text box and calls the Change event procedure
whenever a user makes any changes in the text box. One of the most common uses of the Change event
procedure is to warn people that they should not be entering data in specific text box at this moment.
Explain About Label Properties. (2 Marks & 5 Marks)
LABELS
o It is used to display information. The common use is to identify a text box or other control by describing
its contents.
o The icon for a label is the bold, caption letter A, and Microsoft’s suggested prefix for the Name property
of labels is lbl.
o The labels have 34 possible properties. Most of them overlap with the properties for text boxes and
forms.
Example:
 The Caption property that determines what they display. This property is set to be the same as
the default Name property: Label1 for the first label.
 The Name property for the control is used only for the code you write.
 The ForeColor property affects the color of the text that is displayed. BackColor affects the rest
of the label.
Useful Properties for Labels:
Alignment:
31

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 This property has three possible settings. The usual (default) value is 0, which means the text in the
label is left-justified. Set the value of this property to 1, and the text inside the label will be right-
justified; set the value to 2, and the text is centered.
BorderStyle, BackStyle:
 The BorderStyle property has the same two possible values as text boxes. The default value is 0,
indicates the label does not contain border. Set the value to 1, the label resembles a text box.
 The BackStyle property determines whether the label is transparent or opaque.
AutoSize, WordWrap:
 The labels can be made to grow automatically in a horizontal direction to encompass the text. This is the
function of the AutoSize property.
 Set the WordWrap property to True, the label will grow in the vertical direction to encompass its
contents, but the horizontal size will stay the same.
Event Procedures for Labels:
 The labels respond to 18 events. For example, they can respond to clicking, double-clicking, or the
Change event. The most common event procedures for a label are mouse events.
Mouse Event Procedures:
Name Event That Caused It
MouseDown User clicks one of the mouse buttons.
MouseUp User releases a mouse button.
MouseMove User moves the mouse pointer to a control or to a blank area of the form.
Explain About ‘Navigating Between Controls. (5 Marks)
What Is The Use Of Tabindex And Tabstop Property? (2 Marks)
How Can We Assign The Access Key For Text Boxes? (2 Marks)
NAVIGATING BETWEEN CONTROLS
 The mouse is the most common way to move from control to control in a Windows application, but the
applications have to allow for using the TAB key.
 The Tab Order is the term used in a Windows application for the sequence of controls that pressing
TAB moves you through.
 In a VB application, the order in which you create the controls is the order used for the tab order. The
first control create at design time is the one that receives the focus when the application starts.
 The user press TAB when the focus is at the last control that the user created, the focus moves back to
the first control.
TabIndex Property:
 Using this property to change the setting for the tab order both design and run time. If the user set this
value to 0 for a control, this control automatically becomes the first control in tab order, and all the other
controls moved upward in tab order.
TabStop Property:
 This properties consists of two settings i.e. True/False. This property controls whether the user can tab
to the control.
Example:
 If the user set the TabStop property of a command button to False, the user can directly click on
it but wouldn’t be able to tab to it and press the SPACEBAR to activate it.

Accessing Access Keys for Text Boxes:


 The text box does not contain caption property. The labels have captions, so that the user set an access
key for them by using the ampersand (&) in front of the letter.
 If the user presses the access key for a control, such as a label, that does not respond to focus events, the
focus moves to the next control that will accept it in tab order.
 To give an access key for a text box by
 Create a label for the text box.
 Set up the access key for the label.
 Then create the text box.
 If you need to use an ampersand in a label but don’t want to create an access key, set the UseMnemonic
property to False or use a double ampersand (&&) instead of the single ampersand.

32

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Explain About Message Boxes With Example. (5 Marks)


What Is The Use Of Message Box? (2 Marks)
Write Down The Syntax Of Msgbox Command? (2 Marks)
MESSAGE BOXES
 The message boxes display information in a dialog box superimposed on the form. They wait for the
user to choose a button before returning to the application.
 The users cannot switch to another form in your application as long as VB is displaying a message box.
 It should be used for short messages or to give transient feedback. It can hold a maximum of 1,024
characters, and VB automatically breaks the lines at the right side of the dialog box.
Example:
 The application display a message box when the user moves the focus away from a text box before
placing information inside it.
Private Sub Text1_LostFocus()
MsgBox “Enter the Value”
End Sub

 The user can add more informative, title to a message box. The full form of the message box statement
by adding two options to it.
MsgBox MessageInBox, TypeOfBox, TitleOfBox
 The three different groups of built-in integer constants to specify the kind of message box.
Symbolic Constant Value Meaning
vbOkOnly 0 Display OK button only
vbOkCancel 1 Display OK and Cancel buttons
vbAbortRetryIgnore 2 Display Abort, Retry, and Ignore buttons
vbYesNoCancel 3 Display Yes, No, and Cancel buttons
vbYesNo 4 Display Yes and No buttons
vbRetryCancel 5 Display Retry and Cancel buttons
vbCritical 16 Display Critical Message icon
vbQuestion 32 Display Warning Query icon
vbExclamation 48 Display Warning Message icon
vbInformation 64 Display Information Message icon
 Consider the following statement
 MsgBox “Will have Yes and No Buttons”,vbYesNo

 The next group of number controls which button is the default button for the
box.
Symbolic Constant Value Meaning
vbDefaultButton1 0 First button is default
vbDefaultButton2 256 Second button is default
vbDefaultButton3 512 Third button is default
33

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Example:
 MsgBox “Welcome to JAIRAM COLLEGE”,vbOkCancel+vbExclamation+vbDefaultButton2,
“Test Message Box”

 This box contains an exclamation mark icon with Ok and Cancel buttons, and the second button,
Cancel, would be the default button for this form. The title bar of the message box would show the title.
Write Short notes on GRID. (5 Marks)
THE GRID
 The grid is used to accurately position the controls. In order to control the grid, choose Tools|Options
(ALT+T,O) and then go the General page on the options dialog box.
Show Grid:
 The user can turn the grid on or off by changing the
Show Grid setting. The default setting is on.
Grid Width, Grid Height Boxes:
 The width and height text boxes indicate the distance
between grid marks. The default is 120 twips. Change
these both to 60, and the grid becomes twice as fine.
Align Controls to Grid:
 This checkbox determines whether controls
automatically move to the next grid mark or whether
they can be placed between grid marks.
 It is possible to align an item to the grid even if the
users choose this option is off. To do this, select the
control by clicking it once and choosing Format| Align |
to Grid.
Explain About The ASCII Representation Of Forms. (5 Marks)
THE ASCII REPRESENTATION OF FORMS
 All the information about the controls and form is stored in text format that can be read using text editor
or word processor.
 Using the text representation of a program makes it easy to check that the properties of the various
controls and forms are exactly what you want.
Steps:
 Start a new Standard EXE project.
 Set the caption of the form to “Jairam”
 Add the command button in the default size, in the default location, and using the default name of
Command1 by double-clicking on the Command Button tool.
 Add a Click procedure to the command button with a single line of code:
Private Sub Command1_Click()
Print “Never Ever Ever Give Up”
End Sub

 Save the form with the name ASCII.frm


 Right click on the form and open with Notepad to view the ASCII representation as Shown below:

VERSION 5.00
34

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Begin VB.Form Form1


Caption = "Jairam"
ClientHeight = 3015
ClientLeft = 120
ClientTop = 465
ClientWidth = 4560
LinkTopic = "Form1"
ScaleHeight = 3015
ScaleWidth = 4560
StartUpPosition = 3 'Windows Default
Begin VB.CommandButton Command1
Caption = "Command1"
Height = 495
Left = 1680
TabIndex = 0
Top = 1320
Width = 1215
End
End
Attribute VB_Name = "Form1"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Private Sub Command1_Click()
Print "Never Ever Ever Give Up"
End Sub

 The idea of the ASCII form representation is simple: It contains a textual description of the form’s
properties.
 The listing begins with the five version used, followed by the name of the form and the current settings
of all the properties associated with the form.

||**********************UNIT-I COMPLETED********************||

Text Books Referred:


1. Visual Basic 7 from the Ground Up, Gray Cornel
2. Programming With Visual Basic 6.0,Mohammed Azam,2nd Edition.

JAIRAM ARTS & SCIENCE COLLEGE, SALEM-08


STAFF ID: SCS86 CLASS: III B.Com (CA) ‘A’
35

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

SUBJECT: SOFTWARE DEVELOPMENT WITH DATE: 10.07.13


VISUAL PROGRAMMING

UNIT-II
STATEMENTS IN VISUAL BASIC
Explain about the statements with example. (5 Marks)
What Is Statement? (2 Marks)
Discuss About The Comment Line Statement In VB With Example. (2 Marks)
What Is The Use Of End Statement? (2 Marks)

 A statement is an executable combination of tokens. Smallest individual units in a program are known
as tokens.
 The VB can detect many typos only if the Auto Syntax Check turned on in the Editor page of the
options dialog box. If a statement the user entered cannot be analyzed, a message box pops up and often
helps you find out what caused the problem.
 The VB ignores case and spacing, except within quotation marks. The statements in VB rarely use line
numbers, and each statement generally occurs on its own line.
 The lines are limited to 1,023 characters but a statement can be extended to the next line by using the
underscore character _ proceeded by a space at the end of the line.
 The line continuation character should only need the lines that are longer than the width of the screen.
Example:
MsgBox “Jairam College”_
vbOkOnly, “Test Button”
Comments:
 These statements are statements that help explain the code to any users. They are not processed by VB.
 To comment the statement by using single quotation mark (‘)
Example:
Private Sub Command1_Click()
‘This program was written by Chilamb
End Sub
 The comment statement also called as remark statements. We can also use the rem keyword for a
comment.
Private Sub Command1_Click()
Rem comments describing the procedure
End Sub
 To add comments to the ends of lines, it is easier to use the single quotation mark because the Rem form
requires a colon before it.
PrintForm ‘Dump the current window
PrintForm :Rem a bit more cumbersome
 Everything on a line following a comment symbol or the Rem keyword is ignored, regardless of
whether it is an executable VB statement or not.
The End Statement:
 When VB processes an End statement, the program stops. In a stand-alone program, after the
End statement, all windows opened by the program are closed and the program is cleared from memory.
Many professional programmers prefer to use only one End statement in their code. They place this End
statement in the QueryUnload event for the main form.
VARIABLES
1. EXPLAIN ABOUT VARIABLES. (5 Marks)
HOW CAN WE ASSIGN THE VALUES TO THE VARIABLE? (2 Marks)
WHAT IS VARIABLE? (2 Marks)
 A variable is a placeholder to store values during a program’s execution. The variables in VB are
declared using the DIM statement and the following syntax:
 Dim variablename [As type]
Example:
36

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Dim a as Integer
 The name of the variable:
o Must begin with an alphabet.
o Must not have an embedded period or a special character.
o Must not exceed 255 characters.
o Must be unique within the same scope.
Variable Assignment Statements:
 The assignment statement is used to give a new value to the variable. It is also used to copying
information from source to destination. VB uses an equal sign for this operation.
Example: InterestRate=.05
 The variable name always appears on the left of the equality sign, and the value always appears on the
right.
SETTING PROPERTIES WITH CODE
How Can We Set The Properties By Using Code? (5 Marks)
Discuss About Boolean Properties. (5 Marks)
 To change a property setting for a VB object with code, place the object’s name followed by a period
and then the name of the property on the left side of the equal sign, and put the new value on the right-
hand side.
 object. property=value
Examples:
 To blank the value of text button by using the following code:
 Text1.Text=””
 To change the setting for the text property to the text in the quotation marks.
 Text1.Text=”This is the text”
 To change the caption on a command button called command1, by using the following code
 Command1.Caption=”Addition”
 If you want to set a button (command5) to be first button in tab order,
 Command5.TabIndex=0
Default Properties:
 Every VB object has a default property. When referring to the default property the users do not use the
property name.
Example: Text1=”Jairam College”
Boolean Properties:
 This property that take only the value True or False are called Boolean properties.
Example:
 The visible property of a control is a Boolean property. A statement such as
 Command1.Visible=False
the above code hides the command button by resetting the Visible property to be False. The control
stays hidden until VB processes the statement that is
 Command1.Visible=True
The Not Operator and Boolean Properties:
 The usual way to toggle (Change from on to off, and off to on) Boolean properties is with the Not
operator.
 Command1.Visible=Not(Command1.Visible)
 The VB finds the current value of Command1.Visible, and then the Not operator reverses this value;
that is, if the value was True, it changes to False, and vice versa.
DATA TYPES
Explain About The Various Data Types Used In VB. (10 Marks)
What Is The Use Of Deftype Statement? (2 Marks)
 The variables can have a name and data type. The data type of a variable determines how the bits/bytes
representing those values are stored in the computer’s memory. All variables have a data type that
determines what kind of data they can store. The VB handles 14 standard types of data.
String:
37

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 This datatype holds characters. A variable holding a string is called as string variable. To identify the
variables of this type is to place a dollar sign ($) at the end of the variable name:
Example: sname$
 Once the user adds the dollar sign, that variables can only hold strings. It is used to pick up the
information from the text box.
Example: sname$=Text1.Text
 This data type holds 2 billion characters for Variable Length and 65,400 for fixed length.
Integer:
 This datatype holds only small integer values. To identify the variables of this type is to place a %
(percent) sign at the end of the variable name. [Range: -32,768 to 32,767]. It occupies only two bytes of
memory.
Example: mark1%=73
Long Integer:
 This datatype holds a wide range of integers than integer. [Range:-2,147,483,648 and +2,147,483,647]
 To identify the variable of this type is to place an ampersand (&) sign at the end of the variable name. It
occupies twice as much space as the Integer.
Example: LI&=123456789
Single Precision:
 This is the equivalent of the Floating-Point number. It is used to holds numbers with decimal places. To
identify the variables of this type is to place an exclamation point (!) at the end of the variable name.
Example: spv!=12.345
 It occupies 4 byte of memory space and should be used where very high precision is not a must.
Double Precision:
 It occupies 8 bytes of memory space and should be used in applications where the requirement of
precision is very high.
 The identifier used for double-precision variables is a pound sign (#) and also use this sign at the end of
the actual number.
Example: DPV#=12.345#
Currency:
 It is used for holding monetary values. This data type can have 4 digits to the right of the decimal place
and up to 15 to the left of the decimal point.
[Range: -922,337,203,685,477.5808 to 922,337,203,685,477.5807]
 The identifier used for this variable is a “at” sign @ and also use this sign at the end of the actual
number.
Example: CV@=12.345@
Date:
 This data type used to holds date and time data. It occupies eight bytes of memory.
Example: DOB=#December 31, 1978 11:03 PM#
Byte:
 This data type occupies only one byte of memory. It holds the values from 0 to 255. It cannot hold
negative values or numbers larger than 255.
Boolean:
 This datatype accepts only True or False values.
Variant:
 A Variant data type is a variable that can change its type freely. It can accept text, numeric data or byte
etc. It always takes up to 16 bytes, regardless of the type of data stored in it.
Example:
Dim x //Variant by default
x=”200” //String value (“100”)
x=x-70 // Numeric value (130)

38

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Declaring the Type of Variable:


 Declaring the types of variables used in an event procedure before using them.
Example:
Private Sub Command1_Click()
Dim a As Integer
Dim r As Currency
Dim i As Integer
End Sub
 The above declaration was combined into single line
o Dim a, i As Integer, r As Currency
 To give a variable the variant data type, use the Dim statement without any As clause or identifier:
o Dim k ‘Makes k have the variant datatype
OR
o Dim k As Variant ‘More explicit, easier to read
Requiring Declaration of Variables:
 One of the most common bugs in programs is the misspelled
variable name. The user uses a variable without declaring it. The
VB automatically creates a variable with that name. This is called
“Implicit Declaration”.
 To enforce variable declarations before they are used, this can be
done using the “Option Explicit” statement.
 To put the “Option Explicit” statement in the code window by
using the following steps:
o Open the Code window.
o Select the (General) object from the list of objects
presented in the object list box.
o Select (Declarations) from the procedure list box.
o Type Option Explicit.
 After VB processes an Option Explicit command, the user must declared each and every variables used
in the application. If you try to use a variable without declaring it, VB will pop up an error message.
Subtleties of Variable Data Types:
 To use a variant variable, VB temporarily assign it a default value of “empty” and gives it the variant
type. The “empty” value disappears the moment you assign a value to the variable.
 Every other type of a variable also has a default value. For string variables, the default value is null
(empty) string. For numeric variables, the default value is zero.
Changing the Default for the Type of a Variable:
 In VB set the default settings for Variant variables automatically. To change the default variable types
by using the DefType statement.
Example:
DefType Statement Meaning
DefInt A-Z Changes the default- all variables default to being integer variables.
DefStr I-J All the variables beginning with I and J default to being integer variables.
DefStr S-Z All the variables beginning with S through Z default to being string variables.
 The general forms of the various DefType statements are:
o DefLng letter range(for long integers)
o DefSng letter range(for single precision)
o DefDbl letter range(for double precision)
o DefCur letter range(for currency)
o DefStr letter range(for strings)
o DefVar letter range(for variants)
 You can always override the default settings by using an identifier or a Dim statement for a specific
variable. DefType statements get put in the (General) sections of the code.

39

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

WORKING WITH VARIABLES


How Can We Work With Variables? (10 Marks)
Discuss About The Scope Of Variables. (5 Marks)
Scope of Variables:
 Each variable also has a scope. The scope of a variable is the section of the application that can see and
manipulate the variable.
 If a variable is declared within a procedure, only the code in the specific procedure has access to that
variable. This variable doesn’t exist for the rest of the application. When the variable’s scope is limited
to a procedure it’s called local.
 To use a variable with a broader scope, such as one whose value is available to all procedures with in
the same Form or Module. These variables are called Form-wide and can be accessed from within all
procedures in a component.
 The entire application must access a certain variable that variable must be declared as Public. The public
variables have a global scope. To declare a public variable, use the Public statement in place of the Dim
statement.
Scope Private Public
Procedure-level Variables are private to the procedure in Not applicable. The user cannot declare public
which they appear. variables with in a procedure.
Module-level Variables are private to the module in which Variables are available to all modules.
they appear
Having values Persist:
 When Visual Basic reinvokes an event procedure the old values of local variables are wiped out.
Variables that are constantly reset to the initial state are called dynamic variables. These Dynamic
variables are not suitable for all programming situations.
 Suppose the user needs to keep track of how many times a command button has been clicked. You
could have the values persist by using a form-level variable. The solution is to use the static variables in
VB. The static variables are not reinitialized each time invokes the procedure.
 To make a variable static within a procedure, replace the keyword DIM with the keyword Static:
o Static Count As Integer
Example:
 Start up a new project, add a command button to the form and write the following in the Click event
procedure for the command button.
 This procedure uses a static variable to count the number of times that button is clicked and then
displays that number on the form:
Private Sub Command1_Click()
Static Count As Integer
Count=Count+1
Print Count
End Sub
 Since the count was declared as a static variable, every time you click again VB will add one to the
previous count so that it always displays the correct answer.
 If all the variables within the procedure to be static, add the keyword Static before the words “Private
Sub” that start the procedure.
o Static Private Sub Command1_Click()
MORE ON STRINGS
1. DISCUSS ABOUT STRINGS. (5 Marks)
DISCUSS ABOUT ASCII/ANSI CODES. (5 Marks)
 A string is collection of characters enclosed by double quotes. The VB stores that text box information
as a string. To concatenate two strings, use the ampersand (&).
Example:
Name1$=”Ravi”
Name2$=”Kumar”
Name3=Name1$ & Name2$
 The & joins the strings in the order in which you present them. To build up a long string with the & sign
before using it in a message box.
40

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Example 1:
Message=”This program was created by”
Message=Message & “ Stephen Flemming ”
MsgBox Message
Example 2: [Use & in the MsgBox itself]
Message=”This program was created by”
Name3=“ Stephen Flemming”
MsgBox Message & Name3
Evil Type Conversions I: Beware of the + Sign for Strings:
 Many programming languages use a + sign to join together strings. Although the + still works in VB to
join strings together but it lead to incredibly hard-to-find bugs.
Example:
Private Sub Form_Load()
Dim a As String
Dim b
a=”45678”
b=1234
MsgBox a+b
End Sub
 The VB assumes the value of b to be a number. The result also be a number.
ASCII/ANSI Codes:
 A computer does not have one kind of memory for text and another for numbers. Anything stored in the
computer’s memory is actually stored as a number.
 A code for translating text to numbers is called the ASCII code (American Standard Code for
Information Interchange). The ASCII code associates with each number from 0 through 255 a
displayable or control character, although window cannot display all 255 ASCII characters and uses a
more limited set of characters called the ANSI (American National Standard Institute).
 The value of the function Chr(n) is the string consisting of the character of ASCII value n. This
statement
 Print Chr(n)
either displays the character numbered n in the ASCII sequence for the font currently in use.
Example: Print Chr (227) ‘Prints the Greek letter (pi) on the screen.
 The following code uses the ASCII/ANSI value for the quotation mark, 34, to display a sentence
surrounded with quotation marks.
Print Chr(34)
Print “Welcome to Jairam College”
Print Chr(34)
 The Chr function returns a string stored in a Variant. The output of above code is
“Welcome to Jairam College”
 The VB also has a function that takes a string expression and returns the ASCII/ANSI value of the first
character it is Asc. If the string is empty using this function generates a run-time error.
Built-in String Constants:
 The VB consists of various Built-in string constants. They are:
Character Symbolic Constants
Null Character vbNullChar
Carriage return vbCr
Line feed vbLf
Backspace vbBack
Tab vbTab
Vertical tab vbVerticalTab
Form feed vbFormFeed
Carriage return and form feed vbCrLf
Example:
 You can force a break in a message box by setting up the message string using the vbCrLf constant as
shown below:
41

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Message$=”Welcome to”
Message=Message$ & vbCrLf & “Jairam College”
MsgBox Message$
Fixed-Length Strings:
 It is a special type of string; these variables are created with a DIM statement.
Example:
Dim x As String *20  Fixed-length string

 If you assign a string of fewer than 20 characters, the x will be padded with enough trailing spaces to
total 20 characters. If you assign a string that is too long, VB simply truncates the characters. (Trim
function used to remove spaces).
MORE ON NUMBERS
Explain About More On Numbers. (10 Marks)
Discuss About Precedence Of Arithmetic Expressions With Example. (5 Marks)
How VB Treats Numbers Of Different Data Types. (5 Marks)
List Out the Conversion Function In VB. (2 Marks)
 To assign a value to a numeric variable in VB, you cannot use a comma to delineate thousand. If use a
decimal point, but we can assign such a number to an integer or long integer, it will automatically be
rounded to an integer value.
The Numeric Operators:
Operator Operation
+ Addition
- Subtraction
/ Division
* Multiplication
^ Exponentiation
\ Integer division
Mod The remainder after integer division
 The ordinary division symbol / gives the value that is single-precision, double precision, or currency
answer, depending on the object involved. The backslash throws the remainder value and gives the
integer. Example: 7\3=2
 The mod operator provides the remainder after integer division (7 mod 3) =1. When one integer
perfectly divides another the mod operator gives zero (8 mod 2=0).
 The combination of numbers, variables, and operators from which VB can extract a value is a numeric
expression.
Parenthesis and Precedence:
 An arithmetic expression without any parenthesis will be evaluated from left to right using the rules of
precedence of operators. The following list gives the order (hierarchy) of operations:
 Exponentiation(^)
 Negation
 Multiplication and division
 Integer division
 Remainder (Mod) function
 Addition and subtraction
Example:
Expression: 4*2+16/8+2^3^4
Step 1: 4*2+16/8+8^4
Step 2: 4*2+16/8+4096
Step 3: 8+2+4096
Answer: 4106
Arithmetic on Date Variables:
 VB makes it easy to do calculations with date variables.
Example: Dim a As Date
a=Now ‘Gives current day and time
Print a
42

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Print a-1000
How VB Treats Numbers of Different Data Types:
 When the user assigns a variable or value of one type to a variable of a different type, VB does a type
conversion if in can; otherwise it generates an error at run time.
 The below code displays the error message
Dim a as Integer, b as Long
b=1234567
a=b
because the information b is too long to fit into an integer variable. The above code will be rewrite as
Dim a as Integer, b as Long
b=123
a=b
 When the user use numbers in the program and do not assign them to a variable of the variant type, VB
assumes the following:
o If a number has no decimal point and is in the range -32,768 to 32,767 it’s an integer.
o If a number has no decimal point and is in the range for a long integer.
o If a number has a decimal point and is in the range for single-precision number, it is assumed to
be single precision.
o If a number has a decimal point and is outside the range for a single-precision number, it is
assumed to be double precision.
Type Conversions:
 The process of converting one data type to another is called casting. Use built-in function to force a type
conversion from one variable to another-if the values stored are compatible.
 VB will only do a conversion to a numeric type if the result will be in the permitted range for the target
type or if the string is really a number represented in numerals.
 The below conversion function used to convert either a string of numerals to a number or to convert
from one type of variable to another.
Conversion Function Meaning
CInt Converts to an integer
CLng Converts to a long integer
CSng Converts to single precision
CDbl Converts to a double precision
CCur Converts to the currency type
The Val function:
 This function is used to convert a numeric string to a number. It simply reads through the string until it
encounters a non-numeric character. The number you get from it is determined by where it stopped
searching.
Example: Val(“30something”)=30
Converting Numbers Back to Strings:

 Using Str function, convert a number to a string. The Str and Str$ functions convert numbers to strings
but don’t clean them up in any way.
Example:
Str(143)=”123”
Str(143.456)=”143.456”
Evil Type Conversions II:
 Conversion from strings of numerals to numbers. VB’s evil type coercion facility occasionally makes
this neat feature dangerous.
Example:
Dim a As Integer, b as String
a=2
b=”1,234”
a=a*b ‘bug
Print a
NUMBER IN VISUAL BASIC
Bits, Bytes, and Hexadecimal (Base 16) number in Visual Basic:
43

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 The color properties by hexadecimal format base 16. The binary digit contains base 2. Eight bits form a
byte, and half a byte forms a nibble.
Binary Decimal
0 0
1 1
10 2
11 3
100 4
101 5
 To convert binary numbers to hexadecimal format, group of digits from right to left in groups of four
and convert.
Example: 11010111 (1101 0111, in two groups of four) is hexadecimal D7:1101 is 13 in decimal
format and D in hexadecimal format and 0111 is 7 both decimal and hexadecimal formats.
Working with Colors:
 The settings for the color properties are indicated by hexadecimal coding. Every color code in VB is
made up of six hexadecimal digit, from &H000000& to &HFFFFFF&.
Hex Color Code Color
&H0000FF& Maximum Red
&H00FF00& Maximum Green
&HFF0000& Maximum Blue
 To change color settings directly by
o Move to the properties window, and select Backcolor and Forecolor.
o Decide the color
o Enter the appropriate hexadecimal code
CONSTANTS
Explain About Constants With Example. (5 Marks)
What Is Constant? (2 Marks)
 The values do not change throughout the execution of an application is called constant. It is also used
for storing values like variables.
Creating our own Constants:
Syntax:
[Public|Private] Const constantname [As type] =expression
 The constantname should be a valid name.
 As type is the data type.
 The expression is the numeric or string value that has to be assigned to the constant.
Example: Const pi=3.14
Scope of the Constant:
 The constants are declared in the declaration section of the form, standard, or class module. It also
declared by public keyword. (Accessed throughout the application).
 It also declared by with in procedure (Accessed only the procedure).
THE SUPPLIED CONSTANT FILE:
 The VB comes with hundreds of useful constants for working with the
built-in functions, objects, and methods.
 The built-in constants are available for pasting into the code window
from the object browser. The Object Browser pops up when you press F2
or choose Object Browser from the view menu.(ALT+V+O)
 To paste a constant into your code from the Object Browser:
o Make sure the cursor is where you want the constant to appear in
the code window.
o Click on the Copy to Clipboard button in the Object Browser (the third button in the first line)
o Go to where you want the constant in your code and press CTRL+V
INPUT BOXES

44

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

1. DISCUSS ABOUT INPUT BOXES. (5 Marks)


 It is an alternative way of getting information from the
user. It displays a modal dialog box on the screen like
an MsgBox function.
 The above input box consists of two command buttons
OK and Cancel, and a text area at the bottom. VB
always places the focus in this text area with it processes
a statement containing an InputBox function.
Simple Syntax:
o StringVariable=InputBox(promptstring)
 This form uses the name of the project in the title bar of the InputBox.
Full Syntax:
o VariableName=InputBox(prompt[, title] [, default], [, xpos] [, ypos] [,helpfile, context])
 The prompt parameter is a string or string variable whose value VB displays in the dialog box.
 The title parameter is optional and gives the caption used in the title bar. There is no default value; if
you leave this out, the applications name is used in the title bar.
 The default parameter is also optional. It display default text in the Edit box where the user will be
entering information.
 Both xpos and ypos are integral numeric expressions. xpos is the distance in twips between the left edge
of the input box and the left edge of the screen. ypos gives the distance in twips between the top of the
box and the top of the screen.
 The two parameters helpfile and context are used together when you have a help message attached to
the box.
DISPLAYING INFORMATION ON A FORM
How Can We Display The Information On A Form? (10 Marks)
Write Down The General Syntax For Print Method. (2 Marks)
What Is The Use Of CurrentX And CurrentY Property? (2 Marks)
Write down the syntax for textheight and textwidth method. (2 Marks)
 The Visual Basic displays text on a form using Print method. The general syntax for the Print method
 Formname.Print expression
where expression is any visual basic expression that VB can convert to a string.
 To use Print statement in the Form_Load event to display information when the form starts up, you
can’t simply use a Print statement. To print the statement by
 First VB process a Show statement before it processes any Print statements.
 To set the AutoRedraw property to be True.
 Unless the AutoRedraw property of the form is set to True, the text will disappear.
Example:
Private Sub Form_Load()
Show
Print “Jairam College”
End Sub
Now run the above code. Next minimize the form and restore it. The text has disappeared.
 The simplest solution to the problem is to set the AutoRedraw property of the form to be True. One
simple method to fix this problem without using the AutoRedraw property is to simply move the above
code to both the Form_Resize event and Form_Paint event procedures as in the following code.
Private Sub Form_Paint()
Cls
Print “Welcome to VB”
End Sub
Private Sub Form_Resize()
Cls
Print “Welcome to VB”
End Sub
CurrentX and CurrentY:

45

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 Fonts in which all characters are the same width are called non-proportionally spaced fonts; fonts where
characters may be different widths are called proportionally spaced fonts. Courier New is the most
common non-proportionally spaced font and Arial is a common proportionally spaced font. Most fonts
in Windows are proportional.
 The VB always reports the current position as the values of two properties of the form or picture box:
CurrentX and CurrentY.
 CurrentX refers to the horizontal position where VB will display the information.
 CurrentY refers to the vertical position where it will display the information.
 If you change the value of these properties, you change where the next Print statement will display its
information. The CurrentX position to be 100, all text will start 100 pixels over from the left side of the
form.
Example:
FormName.CurrentX=Value
FormName.CurrentY=Value
 Whenever you use the Cls method to clear a form, VB resets the CurrentX and CurrentY values to zero.
After clearing the form using the Cls method, the next Print statement puts information in the top left
corner. Using the above property we cannot specify how much space a character or string in taking up,
so we can use the following built-in methods.

 TextWidth
 TextHeight
 The syntax for the TextWidth method is
 FormName.TextWidth(string)
after processing this statement, VB returns the value for the width of the string inside the parentheses,
using the current font and reporting the results in the current scale.
 The syntax for the TextHeight method is
 FormName.TextHeight(string)
this gives the height of the string inside the parentheses. The TextHeight is used to determine the
amount of vertical space and TextWidth and amount of horizontal space you need to display a string.
 Suppose you want to display information at the beginning of the tenth line of text as it would appear in
the ordinary coordinate system.
 CurrentY=Me.TextHeight(“I”)*9
 CurrentX=0
Example: Centering Text Inside a Form:
 To display a message in the exact center of a form by using the following steps:
o Find the current value of the ScaleHeight and ScaleWidth properties.
o Divide these values in half.
o Find the value of the ScaleLeft and ScaleTop properties for the form.
o Add the results from step 2 to the values from step 3. This gives you the coordinates of the
exact center of the form.
o Use the TextWidth method on the string you want to center.
o Subtract half the value VB obtains form step 5 from the value in step 4, and make this the
value of CurrentX.
o Similarly, subtract half Me.TextHeight(string) from the value of CurrentY obtained in step 5.
Example:
Private Sub Form_Resize()
Dim message As String
Dim w As Integer
Dim h As Integer
Dim l As Integer, t As Integer
Cls
message = "welcome to Visual Basic!"
l = Me.ScaleWidth / 2
t = Me.ScaleHeight / 2
46

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

l = Me.ScaleLeft + l
t = Me.ScaleTop + t
w = Me.TextWidth(message) / 2
h = Me.TextWidth(message) / 2
CurrentX = l - w
CurrentY = t - h
Print message
End Sub
The Font Properties in Code:
 To assign a font name in code, place the name in quotation marks on the right-hand side of an
assignment statement using the Name property of the Font object:
o ObjectName.Font.Name=”Courier New”
o Object.Font.Name=”Arial”
 You can change all the properties of the Font object via code. Except for Font.Size, they are all Boolean
properties. (True or False)
o ObjectName.Font.Size=18
o ObjectName.Font.Bold=True
o ObjectName.Font.Italic=True
o ObjectName.Font.Underline=False
Displaying Tabular Data in a Non-proportionally Spaced Font:
 The Print Zones are always set 14 columns. The VB recalculates this distance depending on the font
characteristics in effect.
 Each time you use a comma in a Print method, VB displays the data to the next print zone.
Example:
Me.Print FirstName$,MiddleInit$,LastName$
tries to have the value of the string variable FirstName$ printed in the first zone, the value of the
variable MiddleInit$ at the beginning of the SecondZone, and the value of the variable LastName$
printed at the beginning of the third zone.
The Tab and Spc Commands and Semicolons:
 Normally, after VB processes a statement involving the Print method, it moves to the next line.
CurrentY increases by the height of the current font and CurrentX is set back to zero. You can also use
an empty Print statement to add a blank line.
 If you want to suppress the automatic carriage return and line feed, place a semicolon at the end of the
statement.
Private Sub Form_Load()
Show
Me.Font.Name = "Courier"
Me.Print "welcome to"
Me.Print "Jairam college"
Me.Print
Me.Print "welcome to"
Me.Print "Jairam college"
Me.Print
End Sub
 The Tab function lets you move to a specific column and start
printing there.
Syntax:
Print Tab(ColumnNumber%);
ColumnNumber% is an integral expression. If the current column position is greater than its value, Tab
skips to this column on the next line. If the value is less than 1, VB moves to the first column.
 The Spc function has a syntax similar to the Tab function:
Spc(Integer%)
this function inserts the specified number of spaces into a line, starting at the current print position and
using spaces the width of an average character. The value inside the parenthesis can’t be negative.
(Unit – II to be Continued…)
47

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

JAIRAM ARTS & SCIENCE COLLEGE, SALEM-08


STAFF ID: SCS86 CLASS: III B.Com (CA) ‘A’
SUBJECT: SOFTWARE DEVELOPMENT WITH DATE:
VISUAL PROGRAMMING

(UNIT-II Continued…)
THE FORMAT (Form) FUNCTIONS
Explain about the format function. (5 Marks)
Write down the syntax for format function. (2 Marks)
Discuss about predefined format strings. (5 Marks)
 The format function works with number and a template also called a format string. The syntax is
 Format(NumericExpression, FormatString$)
Example:
Me.Print Format(123.456789,”###.##”)
 The above statement yields a string “123.46” that will be printed on the form.
Example:
Me.Print “The interest rate is “&Format(payment,”####.##”)
 The above statement the extra space after the work “is” is essential because it does not leave the space
for an implied +sign in front of the number.
 A # is the placeholder for a digit, except that leading and trailing zeros are ignored.
Example:
Me.Print Format(123.450,”###.###”)
The above statement yields 123.45
 If you want to have display leading and trailing zeros, use a zero in place of the # in the format string.
Example:
Me.Print Format(123.450,”000.000”)  Yields 123.450
Me.Print Format(123.450,”0000.000”) Yields 0123.450
 To display number with commas every three digits. For this place a comma between any two-digit
placeholder.
Example:
M$=”Your balance is” &Format(balance, “$###.##”)
 If you need to display a symbol, such as -,+,$, or a space, you use it in the format string exactly in the
place you want it to occur.
Predefined Format Strings:
 Visual Basic makes it even easier to deal with the most common formatting situations by adding what
are called named formats to the Format function.
Example:
Me.Print Format(Amount, “Currency”)
instead of
Me.Print Format(Amount,”###,###.##”)
this is because the Currency named format is defined to be the same as ###,###.##
Name of Format Description
General Number Gives you a string of digits with no thousands separator.
Currency Uses the appropriate thousands separator and displays two digits to the right of the decimal point.
Fixed Displays at least one digit to the left and two digits to the right of the decimal point.
Standard Uses the appropriate thousands separator, and at least one digit to the left and two digits to the
right of the decimal point.
Percent Gives you the number in percentage form. Always displays two digits to the right of the decimal
point.
Scientific Uses Visual Basic’s version of scientific notation.
Yes/No Displays No if the number is 0; otherwise, displays Yes
True/False Displays False if the number is 0; otherwise, displays True
On/Off Displays Off if the number is 0; otherwise display On

48

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 The following table gives you the various formats for date and times.
Name of Format Description
General Date Displays a date and/or time. If there is no fractional part, you get a date. If there is no integer part,
you get a time. If there are both, you get both.
Long Date Displays a date using the format that windows uses for full dates.
Medium Date Displays a date using the middle date format.
Short Date Displays a date using the short date format.
Long Time Displays a time with the hours, minutes, and seconds.
Medium Time Displays time in 12-hour, format using only hours and minutes and AM/PM.
Short Time Displays the time using a 24-hour clock.
Example:
Private Sub Form_Load() Output:
Show
Me.Font.Size = 12
Me.Print Format(Now, "General Date")
Me.Print Format(Now, "Long Date")
Me.Print Format(Now, "Medium Date")
Me.Print Format(Now, "Short Date")
Me.Print Format(Now, "Long Time")
Me.Print Format(Now, "Medium Time")
Me.Print Format(Now, "Short Time")
End Sub
PICTURE BOXES
Explain about picture boxes. (5 Marks)
 Using picture box we can display icons, gifs, jpges, bitmaps, and Windows metafiles. It responds to the
Click and Double-click events. It is also called as “forms within forms”.
Example:
 It have CurrentX and CurrentY properties as well as the same Scale properties as forms,
so you can accurately position text inside them.
 You can mix fonts and font sizes when you print to a picture box.
 You can add controls to a picture box by working with the toolbox in the same way that
you would add controls to a form.
 The main difference between picture and forms is that you use the Height and Width properties of the
picture box rather than the ScaleHeight and ScaleWidth properties of the form.
Example:
Picture1.CurrentX=Picture1.Height/2-TextHeight(“A”)/2
 The main advantages to using a picture box rather than a form to display data are that
 Information displayed in a picture box will not be obscured by any controls on the form.
 It takes less memory.
 You can have more than one picture box on a single form.
Working with picture boxes:
 Picture boxes have 50 properties and respond to 19 events. Example: Font, Visible, Enabled, and so on.
 If AutoSize is True, the picture box will automatically resize itself to fit the image. The Cls method
works in much the same way for picture boxes as it does for forms: it erases whatever image and text
were placed in the picture box while the program was running and resets the CurrentX and CurrentY
properties.
 The Move method lets you move the picture box around at run time. The TextHeight and TextWidth
methods are used, as with forms, to accurately size text in order to position it better.
 There are two ways to display an image inside a picture box (or form) at design time.
 To load a picture by setting the Picture property via the Properties window.
 To paste a picture directly into the picture box.
 To add a picture at run time by two ways:
 To assign the Picture property of one object to the Picture property of the other.
Example: Picture2.Picture=Picture1.Picture
Copies the image from the first picture box to the second.

49

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 Use LoadPicture function to attach a file containing a graphical image to a picture box at run time. The
Syntax for this function is
 PictureBoxName.Picture=LoadPicture([filename])
(Or) for forms
 [FormName.]picture=LoadPicture([filename])
 If you leave out the optional filename, the current image is cleared from the form or picture box. The
filename should include the full path name if the file isn’t in the current directory. The LoadPicture
statement without a filename will also clear a picture that was added at design time.

RICH TEXT BOXES


Discuss about rich textboxes with example. (5 Marks)
List out and discuss about the properties of rich textboxes. (5 Marks)
 It is one of the most useful controls in VB. It is a custom control, you will need to add it to the toolbox
if it not already there. To do this:
 Choose Project| Components to open the components dialog box.
 Choose Microsoft RichTextBox Control 6.0
 It allows you display text with multiple fonts and sizes.
Important Properties for RichText Boxes
 Many of the properties of a RichTextBox are the same as those for the standard TextBox control. It also
consists of some special properties.
Property Meaning
SelLength Returns or sets the number of characters selected.
SelStart Returns or sets the starting point of the selected text.
SelText Returns or sets a string equal to the currently selected text.
SelBold, SelItalic,SelStrikethru, SelUnderline:
 These properties used to display the text either bold, italic, and so on. To change the currently selected
text to bold in a RichTextBox using the default name of RichTextBox1, by
 RichTextBox1.SelBold=True
the above statement makes all selected text to bold. Any text would continue to be bold until the
SelBold property was toggled off with the subsequent statement.
 RichTextBox1.SelBold=False
SelColor:
 This property sets the color of the currently selected text and of all text added after the current insertion
point.
Example:
RichText1.SelColor=vbRed
SetFontName:
 This property lets you change the font.
Example:
RichText1.SelFontName=”Courier”
SelFontSize:
 This property lets you change the size of the currently selected text.
Syntax:
Object.SelFontSize=Size
A RichTextBox Example:
 As an example of using a RichTextBox control, consider the code needed to activate the following
figure:
Option Explicit
Private Sub Form_Load()
Dim message As String
message = "Welcome to Jairam college"
MsgBox message
End Sub

50

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Private Sub Command1_Click()


RichTextBox1.SelItalic = Not (RichTextBox1.SelItalic)
End Sub
Private Sub Command2_Click()
RichTextBox1.SelBold = Not (RichTextBox1.SelBold)
End Sub
Private Sub Command3_Click()
RichTextBox1.SelFontSize = RichTextBox1.SelFontSize + 1
End Sub
Private Sub Command4_Click()
RichTextBox1.SelFontSize = RichTextBox1.SelFontSize - 1
End Sub
THE PRINTER OBJECT
Explain about printer object. (5 Marks)
Explain About The Properties And Methods Of Printer Object. (5 Marks)
 The usual way to send information to a printer is the Print method applied to the Printer object. The
Syntax used to sent text to the printer is
 Printer.Print TextToPrint
 We can also control the font properties in the same way as for forms.
Example:
Printer.Font.Name=”Script”
Printer.Font.Size=18
Useful Properties
Useful Properties and Methods for the Printer
 The printer object consists of 40 properties and 12 methods.
ColorMode:
 This property determines whether a color printer prints in color or monochrome. It consists of two
possibilities:
Symbolic Constant Value Description
vbPRCMMonochrome 1 Prints output in monochrome
vbPRCMColor 2 Prints output in color.
Copies:
 It is used to set number of copies to be printed.
Height,Width:
 This property gives the height and width of the paper. This is measured in twips. You can’t change there
at run time; they are read-only properties.
EndDoc:
 This method tells windows that a document is finished.
Syntax:
Printer.EndDoc
NewPage:
 This method ends the current page and tells the printer to move to the next page.
Syntax:
Printer.NewPage
Page:
 This property keeps track of the number of pages printed in the current document.
PrintQuality:
 It is used to set the quality of the printed output if the printer driver supports it.
Built-in- Constants:
Constant Value Description
vbPRPQDraft -1 Draft resolution
vbPRPQLow -2 Low resolution
vbPRPQMedium -3 Medium resolution
vbPRPQHigh -4 High resolution

51

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

The Printer Collection


 The Printer object is defined to be current default printer. The Printer collection, allows you access all
the printer drivers stored in the system. The number of printers installed is
 Printers.Count
 The syntax for accessing an element of the Printers collection is simply,
 Printers(index)
Where index is a number from 0 to Printers.Count-1
 You can actually change the default printer directly from VB. This is done with the Set command.
 Set Printer=”WinFax 8.0”
Example:
 To find out if any of the the printers in a user’s system are set up to print in color.
Private Sub Form_Load()
For i = 1 To Printers.Count - 1
If Printers(i).ColorMode = vbPRCMColor Then
MsgBox "at least one printer has a color mode"
End If
Next i
End Sub
Printing Information in a Rich Text Box
 The SelPrint method of a RichTextBox lets you print the current formatted contents of a RichTextBox
on the current printer. If the user has selected text in the RichTextBox control, then the SelPrint method
sends only the selected text to the printer. If no text is selected, the entire contents of the RichTextBox
are sent to the printer.
 To print a null string to the Printer in order to “wake it up”
 Printer.Print “”
 A device context is an integer that Windows uses to identify the object. The device context of the
current printer to tell Windows where to send the information.
 RichTextBox1.SelPrint(Printer.hDC)
 The hDC property of the Printer object gets its device context ID.

DETERMINATION LOOPS

Explain about determinate loop. (5 Marks)


Discuss about for next loop. (5 Marks)
What is looping? (2 Marks)
What is determinate loop? (2 Marks)
List out the steps involved in looping process. (2 Marks)
What is the difference between entry-controlled and exit controlled loops? (2 Marks)
Looping:
 It is used to repeat the execution of a block of statements based on the condition. It consists of two
segments. They are:
 Body of the loop
 Control statement
 Repeating an operation a fixed number of times is called a determinate loop.
Difference between Entry-Controlled and Exit-Controlled Loop:
 In the entry-controlled loop, the control conditions are tested before the start of the loop execution. If
the conditions are not satisfied, then the body of the loop will not be executed.
 In the exit-controlled loop, the test is performed at the end of the body of the loop the body is executed
unconditionally for the first time.
Looping Process:
 The looping process consists of the following steps:
 Setting and initialization of a counter
 Execution of the statements in the loop
 Test for a specified condition for execution of the loop

52

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 Incrementing and decrementing the counter


For…Next Loop:
 This loop structure uses a counter that increases or decreases the value of a variable each time the loop
is executed.
Syntax:
For <Counter> = <Start> to <End> [Step value]
[Statements]
Next <Counter>
 The For and Next are keywords that must be used together. The statements between the For and Next
are usually called the body of the loop, and the whole control structure is called For-Next loop. The
keyword For sets up a counter variable, which can be a variable of any VB numeric type.
Example:
Private Sub Command1_Click()
Dim i As Integer
For i = 0 To 10
Print i
Next i
End Sub
Off-by-One Errors:
 The most common type of error when using For-Next loops is the off-by-one Error. When you have this
kind of coding error, instead of performing an operation, for example 500 times as you had planned, the
program seems to perform it 499 or 501 times. The off-by-one errors are sometimes called fencepost
errors.
More on For-Next Loop:
 Using this loop we can increase, decrease the counter by twos, by fractions, or backward. The Step
keyword tells VB to change the counter by the
satisfied amount rather than by 1.
Example:
Private Sub Command2_Click()
Dim a As Integer
For a = 0 To 10 Step 2
Print a
Next a
End Sub

Private Sub Command2_Click()


Dim a As Integer
For a = 10 To 2 Step -2
Print a
Next a
End Sub
Nested For-Next Loops:
 The one for statement within another for
Statement is called as Nested For-Next Loop.
Example:
Private Sub Command1_Click()
Dim d As Integer
Dim s As Integer
For d = 0 To 2
For s = 0 To 2
Print s
Next s
Next d
End Sub

53

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

INDETERMINATE LOOPS
What is indeterminate loop? (2 Marks)
Explain about various forms of do…loop statement. (10 Marks)
 Repeating an operation until you reach a predetermined specific goal or until certain initial conditions
have finally changed is called indeterminate loop.
Relational operators
 These operators are used to check conditions
Symbols Checks (Tests for)
<> Not equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
Looping Statements:
Do… Loop:
 It is used to repeat the execution of a block of statements based on the condition.
Do
Visual Basic Statements
Until condition is met
Sophisticated Indeterminate Loops
 VB provides solution to complicated looping statements.consider the
following example:
Dim Namecount
Namecount = 0
Entry$ = InputBox$("Namo - ZZZ to end")
Do Until Entry$ = "ZZZ"
Namecount = Namecount + 1
Entry$ = InputBox$("Namo - ZZZ to end")
Loop
 Now the user types the first name before the loop starts. Once this is done,
the program does an initial test.
 The loop is entered and 1 starts being added to the counter only if this test
fails. (Notice that this kind of loop also works if there is nothing in the list
except the flag.) Figure shows a picture of what Visual Basic does for this
type of loop.
The Do While Loop
 Visual Basic has other kinds of loops. These loops consist of replacing the keyword Until with the
keyword While.
 This new loop may seem superfluous since you can always change a Do Until into a Do While by
reversing the relational operator.
For example:
Do
Loop Until X$ <> “ ”

is the same as
DO
Loop While X$ = “ ”

and
DO
Loop Until Number > 5

is the same as
Do
54

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Loop While Number <=5


Various forms of Do...Loop:
Syntax I:
Do While <Condition>
< Statements>
Loop
 Test the condition first and if true, executes the statements.
Example:
Private Sub Command1_Click()
Dim a As Integer
Do While (a <= 10)
Print a
a=a+1
Loop
End Sub
Syntax II:
Do
<Statements>
Loop While (Condition)
 It executes the statement first and then tests the condition. The loop executed at least once.
Example:
Private Sub Command2_Click()
Dim b As Integer
Do
Print b
b =b + 1
Loop While (b <= 10)
End Sub
Syntax III:
Do Until < Condition>
<Statements>
Loop
 Tests the condition first and if false, executes the statements. Loop till the condition is False.

Example:
Private Sub Command3_Click()
Dim c As Integer
Do Until (c > 10)
Print c
c=c+1
Loop
End Sub
Syntax IV:
Do
<Statements>
Loop Until (Condition)
 It executes the statements and then tests the condition. The loop will be executed at least once and then
tests the condition. It executes till the condition is false.
Example 1:
Private Sub Command4_Click ()
Dim i As Integer
Do
Print i
i=i+1
Loop Until (i > 10)
55

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

End Sub
Example 2:
Private Sub Command5_Click()
Do
n$ = InputBox("non-zero number? please!")
Number = Val(n$)
Loop Until Number <> 0
End Sub
Example 3:
Private Sub Command6_Click()
Total=0
PassNumber=0
Do
Total=Total+0.1
PassNumber=PassNumber+1
Print PassNumber,Total
Loop Until Total=1
End Sub
Do Loop with And,Or,Not
 These loops are used to combine two conditions. This is most commonly done with And, or and Not
keyword. For example suppose you want to continue a process while a number is greater than zero and a
text box is empty. it’s much easier to say
Example:
Do While Number > 0 And Text1.Text = “”
Than to say
Do Until Number <= 0 And Text1.Text <> “”
While…Wend Loop
 This Loop structure allows performing a series of steps based on a condition.
Syntax: While < condition>
< Statements>
Wend
 The condition is evaluated first. If it is true, the statements in the block are executed. When the Wend
clause is encountered, the control goes to the beginning of the loop, and the condition is tested again.
The block of code is executed as long as the condition is true.
Example:
Private Sub Command5_Click()
Dim i As Integer
While (i <= 10)
Print i
i=i+1
Wend
End Sub
MAKING DECISIONS
Explain about decision making statements. (10 Marks)
Explain about the various control structures in VB. (10 Marks)
 A program is a set of statements that are normally executed sequentially in the order in which they
appear. To change the order of execution of statements based on certain conditions.
 The Visual Basic supports the following Control Statement or Decision Making Statements:
 Simple-If
 If-Else
 Else-If Ladder
 Nesting of If…Else
 Select Case
Simple-If:
 It is a powerful decision making statement, used to control the flow of execution of statement.
56

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Syntax:
If <condition> Then
<Statement>
End If
Example 1:
Private Sub Command1_Click()
If Val (Text1.Text) <=10 Then
MsgBox "Hello"
MsgBox Text1.Text
End If
End Sub
Example 2:
 You can use an If-Then to determine which button was pressed in a message box. Assign the values of
the MsgBox function to a variable and then use If-Then to check the value.
Private Sub Command2_Click()
x = MsgBox("Yes/No", vbYesNo)
If x = vbYes Then
Print "yes button clicked"
End If
End Sub
The Else: ( If Else)
 It is an extension of simple If statement. The condition is true, the statement followed by if are executed
otherwise the else part statement is executed.
Syntax:
If <condition> Then
<Statement-1>
Else
<Statement-2>
End If
Example:
Private Sub Command3_Click ()
If Val (Text1.Text) >=5 Then
Text1.Text = Text1.Text * 5
Else
Text1.Text = Text1.Text + 5
End If
End Sub
Combining conditions
Combining conditions in an If-Then:
 You can also use the keywords And, Or, and Not in an If-Then.
Example:
Private Sub Command4_Click()
If Val(Text1.Text) >= 5 And Val(Text2.Text = 2) Then
Text1.Text = Text1.Text * 5
Else
Text2.Text = Text2.Text + 5
End If
End Sub
The Block If-Then
 To process multiple statements if a condition is True or False is called as Block If-Then structure.
Syntax:
If <condition> Then
<Lots of statements>
Else

57

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

<More statements>
End If
Example 1:
Private Sub Command5_Click()
If Val(Text1.Text) >= 10 Then
Text1.Text = Text1.Text * 2
MsgBox Text1.Text
Text1.Text = Text1.Text * 5
MsgBox Text1.Text
Else
Text1.Text = Text1.Text * 3
MsgBox Text1.Text
End If
End Sub
Example 2:
 You can easily use If-Then to determine whether the user has entered a string in the form of a date or a
number. The procedure depends on the variant data type combined with two new Boolean functions.
(functions that return either True or False)
Private Sub Command6_Click()
Dim dt
dt = Text1.Text
If IsDate(dt) Then
MsgBox dt
Else
MsgBox "please enter the text in the form of a date!"
End If
End Sub
 The IsNumeric function to determine whether the variable can be converted to a number.
Private Sub Command7_Click()
Dim nt
nt = Text1.Text
If IsNumeric(nt) Then
MsgBox nt
Else
MsgBox "Enter numeric number"
End If
End Sub
Example 3:
 To find whether a file or files exist with a specific extension. The functions needed are:
 Dir$(filespec) or Dir(filespec)
 The difference between the two is that Dir$ returns a string and Dir returns a string stored in a variant.
Filespec is a string expression that contains the filename or file pattern- it is not case sensitive.
Private Sub Command8_Click()
x$ = Dir$("*.exe")
If x$ = "" Then
Print "no text files found"
Else
Print "first file found is "; x$
End If
End Sub
 The above code checks whether the current directory contains any .Txt files.
Combining the If-Then with Loop
 We can also use the control statement within the loop structure.
Else-If Ladder:

58

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 There is another way of putting ifs together when multipath decisions are involved. A multipath
decision is a chain of ifs in which the statement associated with each else is an if.

Syntax:
If <condition> Then
<Statement-1>
ElseIf <condition> Then
<Statement-2>
ElseIf<condition> Then
<Statement-3>
Else
<Statement-4>
End If

Example:
Private Sub Command9_Click()
Dim marks As Integer
Dim Grade As String
marks = Val(Text1.Text) / 2
If marks > 79 Then
Grade = "Honours"
MsgBox Grade
ElseIf marks > 59 Then
Grade = "First"
MsgBox Grade
ElseIf marks > 49 Then
Grade = "Second"
MsgBox Grade
Else
Grade = "Fail"
MsgBox Grade
End If
End Sub
 In the above example the condition is evaluated from top to bottom. A true condition is found, the
statement associated with it is executed. When all the conditions become false, then the final else
statement will be executed.
SELECT CASE
Explain about select case with example. (5 Marks)
Select Case…End Select:
 It is used when the program has to execute one of several groups of statement, depending on the value
of an expression.
Syntax:
Select Case testexpression
[Case expression list-1
statement-1]]
[Case expression list-2
statement-2]]
.
.
.
[Case Else
[else statements]]
End Select
 The test expression is an integer expression or characters. The expression list are constant or constant
expressions and known as case labels.
59

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 The select case statement tests the value of a given expression against a list and when a match is found,
a block of statements associated with that case is executed.
 If more than one case expression matches with the test expression, the statements of the first case only
are executed. The case else is executed when if no match is found between the test expression and the
case expression.
Example1:
Private Sub Command10_Click()
Dim b As Integer
b = Val (Text1.Text) / 2
Select Case b
Case 10
MsgBox "good"
Case 8
MsgBox "not good"
Case 6
MsgBox "ok"
Case Else
MsgBox "bad"
End Select
End Sub
Example2:
Private Sub Command11_Click()
Dim a As Integer
a = Val (Text1.Text) / 2
Select Case a
Case Is <= 5
MsgBox "ok"
Case Is > 10
MsgBox “good"
Case Else
MsgBox “Default”
End Select
End Sub
NESTED IF-THEN’S
Explain About Nested If-Then’s With Example. (5 Marks)
 When a series of decisions are involved, use more than one if…else statement in nested form.
Syntax:
If <condition-1> Then
If <condition-2> Then
Statement-2
Else
Statement-3
End If
Else
Statement-4
End if
Statement-5
Example:
Private Sub Command12_Click ()
If Val (Text1.Text) >= 15 Then
If Val (Text2.Text) < 15 Then
Text2.Text = Text2.Text + 7
Else
Text2.Text = Text2.Text + 5
End If
Else

60

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Text1.Text = Text1.Text + 7
End If
End Sub
 In the above example condition-1 is false, the Statement-4 will be executed, and otherwise it continues
to perform the second test.
 If the condition-2 is true, the Statement-2 will be executed; otherwise the Statement-3 will be evaluated
and then control transferred to the Statement-5.
THE GOTO
Explain about GOTO statement with example. (2 Marks)
 VB retains the unconditional jump or GOTO. It is used to transfer control from one place to another
place in a program. It leads to spaghetti code: code that is hard to read and harder to debug. To use a
GoTo in VB, you must label a line. Labels must begin with a letter and end with a colon. They must also
start in the first column.
Example:
Private Sub Command1_Click()
a = InputBox("Enter the value")
If a = 10 Then
GoTo a
MsgBox a
a: Print a
End If
End Sub
STRING FUNCTIONS
Explain about string functions. (10 marks)
How can we find the length of a string? (2 marks)
What is the use of mid function? (2 marks)
Write a program to find the number of periods In a string (5 marks)
Discuss about instr, instrrev function. (5 marks)
 A built-in function is a prepackaged piece of code that accomplishes a single task. The VB consists of
various built-in functions.
String Functions:
 A string is a collection of characters. The VB consists of powerful string-handling functions. The
information in VB text boxes is usually kept as strings or strings contained in variants, string functions
are far more important in VB in many other programming languages.
 To build up a string of spaces or a string of repeated characters. The function
Space(NumberOfSpaces)
gives you a string consisting of only spaces, with the number of spaces determined by the value inside
the parentheses. The function
String(Number, StringExpression$)
where Number specifies the number of times the characters are repeated. The StringExpression specifies
the characters to be repeated. You can also use the extended ASCII/ANSI code in the second position.
Example:
X$=String(10,”a”)
X$=String(10,”abaayvs” ‘ only first character is used.
X$=String(10,22) ‘122=Asc(“Z”)
 The Trim function (Trim$) removes spaces from both the left and right ends of a strings. The
LTrim(LTrim$) removes spaces from the left end, and RTrim(RTrim$)removes spaces form the right.
Example:
A$=” Jairam college “
T=Trim$(A$)
 The LCase(LCase$)function forces all the characters in a string to be lowercase. Similarly,
UCase(UCase$) switches all the characters in a string to uppercase.
Example:
A$=”Jairam college“
B$=UCase$(A$)
61

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Finding the Length of a String:


 The Len() function is used to find the length of a string, where the parentheses following the function
hold the string expression. This function counts the no of characters including all spaces.
Example:
X=InputBox(“Enter a String”)
MsgBox “The String Length is “&Len(X)
Analyzing String with the Mid Function
 All string functions in VB count the first character as being in place one. The VB’s string functions are
“one-based.”
 The Mid function which returns a string stored in a variant, and the Mid$ function, which returns an
actual string.
Syntax:
PostOfString=Mid$(string,start[, length])
PostOfString=Mid(string,start[, length])
 The first entry holds the string (or string expression) you want to cut up (string). Next the starting
position (start) of the characters you want cut off of the string. The optional last position (length)
specifies the number of characters you want to pull out. These last two options can be either integers or
long integers or an expression that VB can round off to lie in this range.
Example:
F=Mid$(“Visual Basic”, 1, 5)  Visua
S=Mid$(“Visual Basic”, 1, 6)  Visual
E=Mid(“Visual Basic”, 8 ,5)  Basic
 If you leave out the last entry, VB retrieves a copy of the rest of the string-starting, of course, from the
position determined by the second entry.
Example:
Mid(“Visual Basic”,8 ,5)  Basic
Mid(“Visual Basic”,8)  Basic
 The Mid function support named arguments, the names of the parameter followed by a colon and an
equal sign, followed by the value which functions take named arguments can be found in the online
help.
Example:
Mid(TheString, start:=5;length:=4)
Example: Counting the Number of Periods in a String
Private Sub Form_Load()
Dim pc%, l%, i%
Dim se$
se$ = InputBox("Enter a string expression that may or may not contain periods")
pc% = 0
l% = Len(se$)
For i% = 1 To l%
If Mid(se$, i%, 1) = "." Then
pc% = pc% + 1
End If
Next i%
MsgBox "you had " & pc% & "periods in that string"
End
End Sub
Mid as a Statement:
 You can use a Mid as a statement to make changes inside the string.
Example:
S$=”PowerBasic”
Mid(S$, 1, 5)  Quick
gives the string variable S$ value is QuickBasic
62

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 The second position controls where the change will start, and the third position controls how many
letters to put out from the string on the right-hand side of the equals sign.
Example:
Mid(S$, 1, 5) =”QuickBasic by Microsoft”
gives the same result as before.
 If the right-hand side has fewer characters than the number given in the third position of the left-hand
side demands, VB changes as many characters as occur on the right-hand side.
Example:
Mid(S$, 1, 5) =”VB”
` gives S$ the value “VBwerBasic”. The mid statement makes changes within a string but never
changes the length of the original string. You can leave out the last position, for example
Mid (“In the beginning “, 8) =”middle was”
Changes the string to
“In the middle was”
The InStr Function
 This function tells you whether a string is part of another string. It also tells you the position at which
the substring starts.
Syntax:
InStr ([where to start,] start to search, string to find)
The optional first position specifies from which position to start the search. If you leave this entry out,
the search automatically starts from the first position.
Example:
Pharse$=”QuickBasic was Visual Basic’s distant ancestor”
X%=InStr (1, phrase$,”BASIC”)
the value of X% is 6, starting at the sixth position.
 The visual basic is search the string starting from the first position until it finds the substring. If it
doesn’t find the string, it gives back a value of 0.
Example:
X%=InStr(1,pharse$,”basic”)
the value of X% is 0. The InStr function defaults to being case sensitive.
Syntax 2:
 InStr([start, ]string1,string2[,compare])
where the compare parameter specifies the type of string comparison. If you set it to 0 then the
comparison is case sensitive regardless of the current setting of Option Compare. If you use the built-in
constant vbTextCompare, you get a case-insensitive comparison again.
Example:
X%=InStr(1, phrase$, “basic”, vbTextCompare)
will always give you the value 6.
The InStrRev Function:
 The VB 6 adds an InStrRev function that starts searching from the back end of the string.
Syntax:
InStrRev(OriginalString, Substring[, Start[,Compare]])
 The Compare option same as InStr function. One common use of InStrRev would be to check the
extension at the end of a filename that a user typed.
Example:
Dim TestFileName As String, Location As Long
TestFileName=”Full.Extension.html”
Location=InStrRev(TestFileName, “.”)
MsgBox “Your extension is “&Mid(TestFileName, Location)
The Nifty (New) Replace Function:
 This function is used to search and replacement tasks. Suppose you want to change the string
 “JavaScript is the best Scripting Language”
To read
 “VBScript is the best Scripting Language”
63

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Example 1:
TestString$=”JavaScript is the best Scripting Language”
TestString$=Replace(TestString$, “JavaScript”, “VBScript”)
Example 2:
S$=”Java is the best programming language”
K$=Replace(S$, “Java”, “Visual Basic”)
Other Uses for the Replace Function:
Syntax:
Replace(Expression,Find,ReplaceWith[, Start][,Count][, Compare]]])
 The optional Start parameter lets you tell VB the position at which to start looking for the string that
needs to be replaced.
 The count parameter specifies the number of times you want to do the substitution if these are multiple
copies of the same string inside the original string.
 If you omit this parameter the default behavior of Replace is to replace all occurrences of the string.
Example:
TestString=”AAAAAA”
TestString=Replace(TestString,”A”,”Z”,1,1)  ZAAAAA
the Compare parameter case-insensitive replacements by using the constant vbCompareText.
 If you use the empty string as your ReplaceWith value, you will remove the substring from the original
string.
Example:
S=Replace(“1-800-555-1212”,”_”, VbNullString)
gives “18005551212”
 The following table summarizes the results from this and other special situations in the Replace
If Resulting String
The original sting is the empty string An empty string (“ “)
The string that you want to replace is an empty string The original string
The Start parameter is greater than the length of the original string An empty string
The Count parameter is 0 The original string
The original string is null An error
function:

The StrComp Function


 This function can be used instead of the relational operators to compare strings.
Example:
X=StrComp(A$,B$) or X=StrComp(A$,B$,vbCompareText)
 It return a value -1 if A$ is less than B$, 0 if A$ equals B$, 1 if A$ is greater than B$, and it is the
reserved constant NULL if one of the strings is empty.
NUMERIC FUNCTIONS
Explain about numeric functions with example. (5 Marks)
 The numeric function in VB is used to manipulate numbers. The Int function gives the floor of a
number- it’s usually called the greatest integer function.
Example: Int(-3.5)  -4
Int(4.5) 5
The (New) Round Function:
 It is used to round off a number. The syntax is
 Round(expression[,NumberOfDecimalPlaces])

64

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

where the optional second parameter allows you to round past the decimal point. If you leave it off, you
get an integer.
Example:
Round(3.7)  4
Round(3.786, 2)  3.79
Other Useful Numeric Functions:
 The additional numeric functions used to perform the mathematical or engineering type calculations.

Sign():
 This function gives you a +1 if what is inside the parentheses is positive, -1 if negative, and a 0 if its
zero.
Example:
Sgn(-5)  -1
Sgn(5)  1
Sgn(0)  0
Abs():
 It gives the absolute value of whatever is inside the parentheses.
Example: Abs(-1) =1=Abs(1)
Sqr():
 This function return the square root of the numeric expression inside the parentheses, which must be
non-negative or a run-time error follows.
Example: Sqr(4)
Exp():
 This function gives e (e is roughly 2.7182) to the power x, where e is the base for natural logarithms,
and x is the value in the parentheses. The answer is single precision if x is an integer or is itself a single-
precision number; otherwise, the answer is a double-precision number.
Log():
 The log function gives the natural logarithm of a number. To find the common log (log to base 10) use
 Log10(x)=Log(x)/Log(10)
Function Result
this gives the common logarithm of the
value inside the e=Exp(1#) Value of e in double precision parentheses.
Trig Functions: Log 10(X) Log(X)/Log(10)
 The VB has the Log a(X) Log(X)/Log(a) built-in trigonometric
function Sin(sine), Cot(X) 1/Tan(X) Cos(cosine), and
Tan(tangent). The Sec(X) 1/Cos(X) only problem is that VB
expects the angle inside the parentheses following the functions to be in radian measure.
 To convert from degrees to radians, you need the value of π. The formula is
 radians=degrees* π/180
 The following table provides the inverse trigonometric functions.

DATE AND TIME FUNCTIONS


Discuss about date and time functions with example. (5 Marks)
 VB has many built-in functions you can use to read the information contained in the system clock about
the time, day, and year. All Date functions support named arguments.
The Date Function:
 This function returns a date of the form month-day-year (mm-dd-yyyy) for the current date. The month
and day always use two digits; the year uses four.
65

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Time Command Effect


 You can also use
Time=”hh” Sets the hour; minutes and seconds are set to 0.
this function as a
Time=”hh:mm” Sets the hour and minutes; seconds are set to 0.
statement to
reset Time=”hh:mm:ss” Sets the hour, minutes, and seconds. the current
date in the system.
Example:
Date=”mm-dd-yyyy” (OR) Date=”mm/dd/yyyy”
Where mm are numerals between 01 and 12, dd are days between 01 and 31, and yyyy are years
between 100 and 9999.
 If you try to reset the date to an illegal date, such as 31 February, you get an “Illegal function call”
message box when you run the program. If the computer has a built-in clock calendar, then to
permanently reset the clock, you may have to use the setup program that came with the computer. The
changes made by Date may remain only until you reboot your computer.
 The Time function returns an eight-character time of the form hh:mm:ss. To reset it, assign a string of
the correct form to Time as shown in the following table. The hours range between 00 for midnight and
23 for 11.00 P.M.

Numeric Calendar Functions:


 The DataValue(String) function yields an expression of Date type representing the date defined by the
string expression inside the parentheses.
Example:
Dim a As Date
a=DateValue(“12-31-1999”)
a=DateValue(“December 31,1999”)
a=DateValue(“Dec 31, 1999”)
a=DateValue(“31 December 1999”)
a=DateValue(“31-Dec-1999”)
 You cannot use this function if the doesn’t make sense. For example,
 DataValue(“2-30-1998”)  gives “Type Mismatch” message at run time.
Function Description
Now Returns the date and time as stored in the system clock
Date Return the current date
Time Returns the current time
 The DataSerial function returns a number that you can use for date calculations.
Syntax: DataSerial(Year,Month,Day)
Year is an integer between 0 and 9999 inclusive, Month is an integer with a value between 1 and 12, and
Day should be some number between 1 and 31 depending on the month.
Example: DataSerial (1998, 1, 35)  gives you a date in February.
The Format function applied to any date expression to display the information contained in the number.
Example: Format(Now,”m/d/yy”)  7/30/10
Format(Now, "hh:mm")  16:03
Format(Now, "hh:mm AM/PM")  04:04 PM
Format(Now, "hh:mm AM/PM mm/dd/yy") 04:04 PM 07/30/10

FINANCIAL FUNCTIONS
Explain about financial functions. (5 Marks)
 The VB comes with a library of financial functions for handling standard calculations that everyone will
occasionally need to do.
 The Pmt function returns the payment for an annuity based on periodic, constant payments and a
constant interest rate. The annuity is a term for a series of payments made overtime.
Example:
66

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 When you have a mortgage, you start out with a (large) amount, make (many) payments over
time, and end up with a zero balance.
Syntax:
Pmt(RatePerPeriod,NumPeriods,WhatYouStartWith,WhatYouEndUpWith,WhenDoYouPay)
Example: X=Pmt (.08/12, 30*12, 100000, 0, 1)
 RatePerPeriod  Usually the interest rate is quoted per year.
 NumPeriods  This is the number of periods.
 WhatYouStartWith  In a mortgage, this would start out as the balance(Initial balance)
 WhatYouEndUpWith  In a mortgage, this would be zero.
 WhenDoYouPay  Do you pay at the beginning of the period or at the end. Use a 0 for the
end of the month and a 1 for the beginning.
Other Financial Functions:
 FV:This function returns the future value of annuity based on periodic payments and a constant interest
rate.
Syntax: FV (rate, nper, pmt [, pv [, type]])
(OR)
FV(InterestRatePerPeriod,NumPeriods,PaymentPerPeriod[,StartAmount[, WhenDue]])
Example: Retirement calculation
For all financial functions, moneys paid out will be given by negative numbers; moneys received are given
by positive numbers.
 IPMT: This function gives the interest paid over a given period of an annuity based on periodic, equal
payments and a constant interest rate.
Syntax: IPMT(rate,per,nper,pv,fv,due)
Where rate is the interest rate per period, and per is the period in the range 1 through the number of periods
(nper).
Example:The interest paid in first month of the third year of a 30-year $100,000 mortgage at 8 percent is
 IPMT(.08/12,25,360,100000,0,1)
 NPer:This function tells you how long it will take to accumulate an annuity.
Syntax: NPer(rate,pmt,pv,fv,due)
Example: Suppose you are getting 5 percent on your money and you have $100,000 in the bank. To
calculate how long it would take to spend the $100,000 that you have saved if you withdraw the money at
a rate of $1,000 a month, use
 NPer(.05/12,-1000,100000,0,1)
 PV:This function tells you how much periodic payments made over the future are worth now. (The
technical term for this is present value)
Syntax:
PV(rate,nper,pmt,fv,due)
 The rate is the interest rate per period, nper is the total number of payments, pmt is the number of
payment made each period and fv entry is the future value or cash balance you want after you’ve
received the final payment.
Example: PV(.06/12,120,-1000,0,1)
 NPV:This is the net present value function. This function is used when you start out by paying money as
startup costs but then get money is succeeding years.
Syntax:
NPV(RatePerPeriod, ArrayOf())
 To fill the array with the appropriate values in the correct order. The first entry could be negative
number representing startup costs and the remaining entries a positive number representing value
received. At least one entry must be positive and one entry must be negative.
 Rate: This function gives the interest rate per period for an annuity.
Syntax:
Rate(nper,pmt,pv,fv,due,guess)
The Remaining Financial Functions:
 SLN and DDB: These functions return the straight line and double declining balance depreciation of an
asset over a given period.
Syntaxes: SLN(Cost,SalvageValue,LifeExpectancy)
67

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

and
DDB(Cost,SalvageValue,LifeExpectancy,PeriodOfCalculation)
 IRR and MIRR: The IRR gives the ordinary internal rate of return, and MIRR gives the modified rate in
which you allow payments and receipts to have different interest rate.
Syntaxes: IRR(ValueArray(),Guess)
and
MIRR(ValueArray(),FinanceRate,ReinvestRate)
 The ValueArray() contains the receipts and disbursements and must contain at least one negative value
and one positive value. Start with a guess of 1 percent (.01)

||******************Unit – II Completed******************||

Text Book referred:


1. “Visual basic 6 From the Ground up” by Gray Cornell
JAIRAM ARTS & SCIENCE COLLEGE, SALEM-08
STAFF ID: SCS86 CLASS: III B.Com (CA) ‘A’
SUBJECT: SOFTWARE DEVELOPMENT WITH DATE:
VISUAL PROGRAMMING

UNIT-III
FUNCTION PROCEDURES
Explain about function procedures. (10 Marks)
List out the two kinds of general procedures in VB. (2 Marks)
What is Function? (2 Marks)
What is a Sub Procedure? (2 Marks)
 There are two kinds of general procedures in VB. They are:
 Function Procedures
 Sub Procedures
 The function procedures, or user-defined functions, as a self-contained piece of code designed to
message data and return a value.
 The sub procedures are smaller “helper programs” that are used called as needed. Sub procedures are
thus generalizations of the event procedures. Unlike functions, which normally return values,
procedures simply do things.
 Both sub and function procedures perform the following:
 Help you break down larger tasks into smaller ones.
 Automate repeated operations.
 Make it clearer what it is you are trying to accomplish by “naming” a piece of code.
All these features can dramatically reduce debugging time.
Function Procedures:
 Defining your own functions when you use a complicated expression more than once in a project.
 To generate a random integer between 1 and 10
 ri=Int((10*Rnd)+1)
 Suppose the same program needs a random integer between 1 and 40.
 ri=Int((40*Rnd)+1)
Writing a Simple Functions
 To add the function to the current form by
 Open the code window by double-clicking anywhere in the form or by pressing F7.
 Choose Tools | Add Procedure from the Tools menu. This pop up the Add procedure
dialog box.

68

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 Click the Function radio button and type a name for your function. [Example:
RandomRange]
 Click on OK, and a function template for the form as shown in the following figure:

 Now add the code to the function.


Public Function RandomRange(x) As Integer
Randomize
RandomRange=Int(x*Rnd)+1
End Function
 The first line of the function is called the header of the function. The keyword Public is called as
access specifier. The more restrictive access specifier Private, because that specifier is the default for
event procedures. The above function the x is called the formal parameter.
 When naming a function you must follow the same rules as you would for naming variables in VB. The
body of the function-the code that actually defines the function’s power. In the body of the function,
you’ll always want a line that assigns a value to the function using its name.
 RandomRange=Int(x*Rnd)+1
this assignment statement is how the function gets its value. To print a random integer between 1 and
10, you can write.
 Print RandomRange (10)
The VB substitutes the value 10 for the placeholder x everywhere it appears in the body of the function.
More on Parameters:
 In the above example the parameter is a variant because we have not used any type identifier. If we want
sent integers to the function by using the following:
 Public Function RandomRange(x as Integer) As Integer
 We replaced the parameter with a number. To replace the formal parameter with an expression.
Example:
N%=RandomRange (A*B+3)
(A=3 and B=2)
N%=RandomRange (9)
 The value you send the function is sometimes called the actual parameter.
Functions With More Than one Parameter:
 It is possible to pass more than one parameter to a function.
Example:
Public Function RandomRange(x As Integer, y As Integer) As Integer
Randomize
RandomRange = Int((y - x + 1) * Rnd) + x
MsgBox RandomRange
End Function
 Now the RandomRange is called as shown below:
o Number%=RandomRange(5,7)
69

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Going Further with User-Defined Functions


 The simplest form of a function definition is
o Public Function FunctionName(parameter 1, parameter 2, …)
Statements
FunctionName=expression
Statements
FunctionName=expression
Statements
Etc.
End Function
Where parameter1, parameter2, and so on are variables. The types of the parameters can be specified by
type-declaration tags or with As phrases. If VB ever encounters code like.
FunctionName (YourExpressionForParameter1, YourExpressionForParameter2,…)
in any VB statement, then the value of YourExpressionForParameter1 is assigned to all occurrences of
parameter1 inside the body of the function, the value of YourExpressionForParameter2 is assigned to all
occurrences of parameter2 inside the body of the function, and so on.
 Immediately after processing a line with this kind of statement, VB sends the information to the
function definition. It then executes the statements in the body of the function definition using the
information contained in the parameters; the last value assigned to the FunctionName inside the body of
the function in the one VB uses as the result of the function.
 The type of the value returned by the function is specified with a type-declaration tag
(% , !, &, #, or $) appended to the function name, or the named used in the As clause at the end of the
Function line, or by a DefType statement appearing above the Function definition.
 If your user-defined function takes no arguments, you can leave off the parentheses when you assign it
to a variable.
Example:
Public Function RandomRange(x) As Integer
Randomize
RandomRange=Int(x*Rnd)+1
End Function
then you can use either
x=RandomRange
(OR)
x=RandomRange()
in your code to call the function.
 You can only a call a function when you the same number of arguments as there are parameters in the
definition of the function. Each variable that you want to send to a parameter must be of the same type.
 An integer variable argument can be passed to an integer parameter. You could not pass it directly to a
long integer parameter of a function. You can use any type of variable if the parameter is of the variant
type.
Example:
Private Sub Command1_Click()
Dim f As Integer
f = 37
Print test(f)
End Sub
Public Function test(a As Long)
test = a + 1
End Function
 If you do, you will get the error message box.

70

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 The following call statement to test will not produce any error message that is it works very fine.
Scope of Variables Used in Function Procedures:
 The form-level variables are visible to all the functions attached to that form. Any variable dimmed
inside the body of a function procedure will be local to the procedure regardless of whether there is a
form-level variable with the same name.
 The parameters of the function are automatically local; they don’t need a Dim statement.
Example:
Public Static Function AnExample(f As Integer) As Integer
Dim count As Integer
End Function
 The variables f and count will have no relation to any other variables named f and count outside the
function.
 In addition to local variables, you can also have static variables inside your functions. You can make
all the variables in a Function Procedure static by putting the keyword Static before the name of the
function.
Public Static FunctionName(parameter list)
Leaving Functions Prematurely:
 Sometimes you are forced (or want) to exit a function prematurely; you can do this with the Exit
Function statement.
Example:
Public Function pre(x) As Single
If x < 0 Then
Exit Function
Else
Statements
End If
End Function
 This function bails out if a negative value is sent to it. Calling the function with a negative value returns
a value of 0-the default value of any numeric variable.
Sub procedures
Explain about sub procedures with example. (5 Marks)
 To define a Sub Procedure in much the same way you would with a Function Procedure. Use Tools|
Add Procedure. Now click the Sub option button.
 The structure of the simplest kind of Sub Procedure is,
 Public Sub proce()
‘Many print statements
End Sub
 The first line of the Sub procedure is called the header. Next in the header is the keyword Sub followed
by the procedure’s name. Headers can have access specifiers. The name of the Sub procedure also must
follow the rules for variable names.
 The parameter list, enclosed in parentheses, for the information the Sub Procedure will use. After the
header are the lines that contain the statements that make up the procedure. These statements are also
called the body. Finally, there are the keywords End Sub used to indicate the end of a general procedure.
 You can call the Sub Procedure, by using the name of the procedure, followed by the arguments
(parameters), separated by commas if there are two or more:
 NameOfProcedure Argument1, Argument2, ….
(OR)
 Call NameOfProcedure(Argument1, Argument2,…)
71

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 You can use the Call keyword, you must use parentheses around the argument list; when you omit the
Call keyword, you must omit the parentheses.
 If the parameter is not a variant, then any variables must be of the exact same type as the ones you
specified for the parameters.
Summary of how to Code and Use Sub Procedures:
 A sub procedure is a part of a program that performs one or more related tasks, has its own name, is
written as a separate part of the program, and is accessed by using its name followed by the correct
number and type of parameters separated by commas. A sub procedure must have the form.
Sub SubProcedureName(parameter1, parameter2,…)
Statements
End Sub
 Next, when VB executes statements of the form.
SubProcedureName(parameter1, parameter2,…) (OR)
Call SubProcedureName(parameter1, parameter2,….)
Example:
Sub ManyBeeps(X as Integer)
Dim I As Integer
For I=1 to X
Beep
Next I
End Sub
 Since I is dimensioned inside the procedure, it is a local variable, now we can write:
ManyBeeps 10 (OR) Call ManyBeeps(10)
JAIRAM ARTS & SCIENCE COLLEGE, SALEM-08
STAFF ID: SCS86 CLASS: III B.Com (CA) ‘A’
SUBJECT: SOFTWARE DEVELOPMENT WITH DATE:
VISUAL PROGRAMMING

(UNIT-III Continued…)
ADVANCED USES OF PROCEDURES AND FUNCTIONS
Explain about the advanced uses of procedures and functions. (10 Marks)
Discuss About Passing By Reference And Passing By Value. (10 Marks)
Passing by Reference, Passing by Value:
 There are actually two ways to pass arguments to a function variable as an argument. These are called:
1. Passing by reference
2. Passing by value
 When you pass an argument variable by Reference, any changes to the corresponding parameter inside
the procedure will change the value of the original argument when the procedure finishes.
 When you pass an argument by Value, then the original variable retains its original value after the
procedure terminates-regardless of what was done to the corresponding parameter inside the procedure.
Example:
Sub Triple(Num As Integer)
Num = 3 * Num
Print "I am in the Procedure (pass by reference) and "
Print "the parameter variable has value " & Num
Print
End Sub
Sub Form_Load()
Dim Amt As Integer
AutoRedraw = True
Amt = 2
Print "I am in the Form_Load and " & " the variable is now " & Amt
Print
Triple Amt
Print "I called the procedure and the variable " & " is now " & Amt
72

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

End Sub

 So the value of Amt variable has been changed because only one memory location is involved for both
Amt and Num.

 Now the previous Form_Load procedure with the key statement changed to Triple(Amt). So that the
variable Amt is passed by value because it is surrounded by parentheses.

 This time two memory locations are involved one for Amt and another for Num. VB sets aside a second
temporary memory location for the parameter Num.
 This location exists only for the procedure’s use and VB copies the value of Amt into this location.
After VB finishes processing the code in the procedure, Num’s temporary memory location is
reclaimed.
 Since only the value in the temporary memory location (Num) was actually tripled, the value of the
original variable Amt remains the same as it was before we called the procedure.

 When VB leaves any procedure, it releases the memory locations it had temporarily set aside for all
variables that were passed by value.
 If some of the variables sent to a procedure or function never be passed by reference, you can specify
that they will only be passed by value. To do this, add the ByVal keyword before the parameter in the
argument list of the function or procedure.
Example:
Function Example(X As Integer, ByVal y As Single)
 In this example, any integer variable passed to the parameter X may be passed by reference (the default)
or by value(when enclosed in parentheses), but any single-precision variable passed to the parameter Y
will always be passed by value, whether or not it is enclosed in parentheses.
Sub programs that have Optional Arguments:
 VB permits you to have optional arguments in the functions and procedures you define yourself, just as
it does in some of its functions. Optional arguments can be of any type, but they must be the last
arguments in a function or procedure.
Example:
Sub ProcessAddress(Name As String, Address As String, Optional zipplus4 As String)
 In the above example zipplus4 is optional. You can even provide a default value for any optional
argument.
Example:
Sub ProcessAddress(Name As String, Address As String, Optional zipplus4 As String=”0000”)
73

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 In this example, the value “0000” will be used when you don’t send a zipplus4 code to the procedure.
 You can use the IsMissing Function to determine if a Variant Parameter is missing.
Syntax: IsMissing(argname)
The argname must contain the name of an optional variant procedure argument.
Sub ProcessName(FirstName As String, LastName As Variant)
If IsMissing(LastName) Then
MsgBox “we really need your middle initial!”
End If
End Sub
USING THE OBJECT BROWSER TO NAVIGATE AMONG YOUR SUBPROGRAMS
How can we navigate the subprograms using object browser? (5 Marks)
 One of the easiest ways to navigate through the code in your project is with the Object Browser.
Steps:
1. Bring up the Object Browser
2. Choose your project by name from the libraries/projects list box.
3. Up to now all our projects have a single form and all the code is attached to that form. The name
of the form will be same as the value of the form’s name property and when you click on it, the
members(second) column of the Object Browser will show the procedures attached to that
form(including the event procedures) . Double-Click on the name of the subprogram whose code
you want to work with.
 The easiest ways to hide the Object Browser is to right-click inside of it and then choose Hide from its
context menu. Supply the description of your procedures that can show up in the Object Browser.

 To add these descriptions, you can work from the Code Window or the Object Browser itself. To work
from the Object Browser do the following steps:
1. Highlight the function or procedure you want to document.
2. Right click and choose properties from the Context menu that pops up.
3. In the Procedure attributes dialog box shown here, enter the description you want in the
Description text box.

 To work from the code window:


 Make sure the cursor is inside the code for the procedure.
 Choose Tools| Procedure Attributes
 To name your project something other than the default, project1, so that you will see a more descriptive
name in the Object Browser. To do this:
 Choose Project | Properties
 Enter the name you want in the Project Name text box in the dialog box.

74

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

LISTS: ONE-DIMENSIONAL ARRAYS


Explain about one-dimensional arrays. (10 Marks)
Discuss about fixed and dynamic arrays. (5 Marks)
How do you allocate space for a dynamic array? (2 Marks)
What is the use of erase statement? (2 Marks)
 In visual basic, a one-dimensional array is a collection of variables, each one of which is identified by
two things:
1. The name of the array
2. The position of the item on the list
Example:
Errand$(3)-The name of the list is Errand$. The dollar sign $ that indicates that the variables on
this one-dimensional array will hold strings.
 The number in the parenthesis is usually called a subscript, a pointer, or most commonly, an index.
 The one-dimensional arrays in VB default to having a zeroth entry. M(5) is actually the sixth element in
the one-dimensional array M(0)…M(5). Its share the same name but has a different index.
Fixed Versus Dynamic Arrays:
 There are two kinds of arrays in VB:
1. Fixed Arrays:where the memory allocation stays the same for the whole time the program runs.
2. Dynamic Arrays:where you can change size on the fly while the program is running.
 The advantage of a fixed array is that since memory is set aside at the beginning of the program, you run
a much smaller risk of running out of memory while the program is running.
 The advantage of dynamic arrays is the flexibility you can make both fixed and dynamic arrays visible
to the whole application, to a specific form or module, or only within a function or procedure.
 To set up a fixed one-dimensional array visible throughout the whole form, place a statement such as
 Private Errand$(13) (OR) Private Errand(13) As String
in the Declarations section of the form.
 To set up a dynamic one-dimensional array that will be visible to all functions or procedures in the
form, place a statement such as
 Private Errand() As String
in the Declarations section of the form. The empty parentheses; this is what distinguishes a dynamic
array from a fixed array.
Allocate Space For a Dynamic Array:
 Once you have created a form-level dynamic array, you use the ReDim statement inside a function or
procedure to allocate the space.
Example:
Private Errand() As String
Private Sub NameOfProcedure()
Dim Number As Integer
Number=CInt(InputBox(“How many items?”))
ReDim Errand(Number)As String
End Sub
 The above sub procedure asks the user for the number of items and then sets that many spaces aside. If
the program’s memory requirements are very large, it’s possible that VB won’t have enough room for
the array. If this happens, you’ll get the dreaded “out of memory” error.
Preserving Information in a Dynamic Array When Resizing:
75

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 You will often need a way to increase the size of a form-level dynamic array inside a function or
procedure without losing the information that is already in it. We can do this with a variation on the
ReDim command to ReDim Preserve.
Example: ReDim Preserve Errand (11) As String
in a function or procedure to increase the number of entries in the array Errand() to 11 without losing
the first 10 items. Similarly, the statement
ReDim Preserve Errand (9) As String
drops off the last entry in the Errand one-dimensional array but preserves all the others.
Local Arrays:
 You use a local array when you want to keep the information hidden in a single function or procedure
and there by avoid side effects. To set up a local fixed array, simply use the Dim statement inside the
function or procedure with the size.
Example:
Private Sub ProcedureName()
Dim Errand(13) As String
End Sub
 To set up a local dynamic array, use the appropriate ReDim statement in the function or procedure.
 VB allocates space for that array only while the function or procedure is active and reclaims space as
soon as the function or procedure ends.
Private Sub ProcedureName()
Dim DynamicLocalArray() As String, Temp As Integer
Temp=CInt(InputBox(“How many items?”))
ReDim DynamicLocalArray(Temp) As String
….
End Sub
Static Arrays:
 An array, whose contents remain the same no matter how often the function or procedure is used, is
usually called a static array.
 To set up a static array inside a function or procedure, you use the Static keyword:
Private Function FunctionName () As String
Static Errand(13) As String
End Function
 The information you store in a static array remains intact.
Some Ways of Working with One-Dimensional Arrays:
 Values inside one-dimensional arrays are most often assigned by using a For-Next loop or, Do loop
Static Errand(29) As String
Index = 0
Do
NextErrand$ = InputBox("Enter the string")
If NextErrand$ <> "zzz" Then
Errand(Index) = NextErrand$
Index = Index + 1
End If
Loop Until Index = 30 Or NextErrand$ = "zzz"
NumberOfItems = Index
 In the above example, the temporary variable, NextErrand$, is set up to hold the information before it is
added to the one-dimensional array.
 Once you know the entry is acceptable, we fill in the entry and move the index up by one. This process
continues until the index becomes 30 or NextErrand$ is zzz.
The Erase Statement
 VB allows you to reclaim the space used by a dynamically dimensioned array done with the Erase
statement.
Example: Erase Errand  would erase the Errand array and free up the space it occupied.

76

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 If an array were not dimensioned dynamically the Erase command would simply reset all the entries
back to zero for numeric one-dimensional arrays, to the null string for string one-dimensional arrays,
and to null for variant one-dimensional array.
 Using the Erase command on a fixed or static one-dimensional array gives a fast method to “zero out”
the entries. (It sets them to the null string for string arrays.)
One-Dimensional Arrays with Index Ranges
 VB has a command that eliminates the zeroth entry in all one-dimensional arrays is done by the Option
Base 1 statement. This statement is used in the Declarations section of a form or module, and it affects
all one-dimensional arrays in the module.
 All new one-dimensional arrays dimensioned in that form or module will begin with item 1. After
Option Base 1, Dim Errand$(30) sets aside 30 spots rather than 31.
Example: Dim SalesInYear(1980 To 1997)
 The array will have 18 boxes labeled SalesInYear(1980), SalesInYear(1981),….SalesInYear(1997). The
keyword To marks the range to be used for the indexes. Put the smaller number first. You can use both
positive and negative long integers for the range.
 Finally, you can always find out the lower index or upper index in an array by using the commands
LBound and UBound. LBound gives the lowest possible index and UBound the highest in a list.
Dim f (3 To 35)
Print “Lower bound of f is “ & LBound(f)
Print “Upper bound of f is “ & UBound(f)
Iterating Through Array Entries:
 VB allows you two ways to construct a loop that iterates through all the elements in an array. The
fastest is to use the LBound and UBound functions in a loop:
Dim I As Integer
For I =LBound(AnArray) To UBound(AnArray)
…..
Next I
 “For each” to walk through the items in an array. The format for a For-Each that works through the
items in an array looks like this:
Dim Item As Variant
For Each Item In AnArray
…..
Next
where the Item variable must be a variant. For-Each for an array is so much slower than using a For-
Next.
Assigning Arrays:
 One of the more useful features added to VB6 is the ability to make array assignment. Suppose you
have a dynamic array called MyErrands and another called YourErrands that hold the same type of
information.
 MyErrands=YourErrands
will automatically change the size of the dynamic array named MyErrands to be the size of the array
YourErrands and copy all the information from YourErrands into the corresponding slots in the
MyErrands array.
Example:
ReDim M(1 To 10) As String
Dim f(3 To 37) As String
Print “Lower Bound of M is “ & LBound(M)
Print “Upper Bound of M is “ & UBound(M)
M=f
Print “Lower Bound of M is now “ & LBound(M)
Print “Upper Bound of M is now “ & UBound(M)
The Array Function:
 It is possible to store an array in a variant. This technique gives you a quick way to swap the contents of
two nondynamic arrays.
Example:
77

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Dim i As Long
Dim a(1 To 20000) As Long
Dim b(1 To 20000) As Long
For i = 1 To 20000
a(i) = i
b(i) = 2 * i
Next i
Dim array1 As Variant, array2 As Variant, temp As Variant
array1 = a()
array2 = b()
temp = array1
array1 = array2
array2 = temp
Print "the third entry in array1 is now” & array1 (3)
 If you want to create an array in a variant directly use the Array function.
Syntax: Array (arglist)
where the arglist argument consists of a list of items separated by commas.
Example:
Dim A As Variant
A=Array(1,2,3,4,5)

ARRAYS WITH MORE THAN ONE DIMENSION


Explain about arrays with more than one dimension. (5 Marks)
 Arrays with more than one dimension; they’re usually called multidimensional arrays.
 The list of data lead to a single subscript (one-dimensional arrays), tables of data lead to double
subscripts (two-dimensional arrays).
Example: To store a multiplication table in memory- as a table with the following code:
Static MultTable(1 To 12, 1 To 12) As Integer
Dim I As Integer, J As Integer
For I = 1 To 12
For J = 1 To 12
MultTable(I, J) = I * J
Next J
Next I
 The first entry as giving the number of rows and the second as giving the number of columns. The VB
allows you up to 60 dimensions with the Dim statement and 8 with the ReDim statement.
 Example: Dim LargeArray%(2,2,2,2,2,2,2,2)
 The following would give you a sales table for the months in the year 1990 to 1997:
 Dim SalesTable(1 To 12, 1990 To 1997)
 ReDim for multidimensional arrays in exactly the same way as with one-dimensional arrays.
 Example: ReDim LargeArray%(2,2,2,2,2,2,2,2)
 You can have index ranges in multidimensional arrays; the following commands are used to find the
upper bound and lower bound in each dimension.
 LBound(NameOfArray,I)
 UBound(NameOfArray,I)
gives the lower and upper bounds for the I’th dimension of the array.
Dim Test%(1 To 5, 6 To 10, 7 To 12)
Print LBound(Test%, 2)
gives a 6 and
Print UBound(Test%, 3)
gives a 12
USING LISTS AND ARRAYS WITH FUNCTIONS AND PROCEDURES
How can we pass the array to a function and procedure? (5 Marks)
What is the use of paramarray keyword? (2 Marks)

78

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 VB has an extraordinary facility for using lists and arrays in procedures and functions. Arrays are
always passed by reference.
 This means any changes you make to the array or to the entries in the array will persist after VB leaves
the function or procedure.
 The arrays passed by reference you don’t need to use form-level arrays unless you want the array to be
visible everywhere.
 To send an array parameter to the procedure or function, just use the name of the array followed by
opening and closing parentheses in the list of parameters.
Example:
 Private Sub Example(List#(), Array$(),BigArray%(), X%)
Where List# is a one-dimensional array of double-precision variables, Array$ is a two-dimensional
string array, and BigArray% is a three-dimensional array of integers.
 The above example would allow the procedure to use a list of double-precision variables, an array of
strings, a three-dimensional array of integers, and a final integer variable. To call the procedure, you
might have a fragment like this:
 Dim PopChange#(50), CityState$(3,10), TotalPop%(2,2,2)
Now
 Example:
PopChange#(), CityStates$(), TotalPop%(), X1#
would call the procedure Example by sending it the current location of the three arrays and the integer
variable.
Example:
To write a function procedure that would take a list of numbers and return the maximum entry.
Function FindMax(A() As Single) As Single
Dim Start As Integer, Finish As Integer, I As Integer
Dim Max As Single
Start = LBound(A)
Finish = UBound(A)
For I = Start To Finish
If A(I) > Max Then Max = A(I)
Next I
FindMax = Max
End Function

The ParamArray Keyword: Procedures with a Variable Number of Arguments


 It is sometimes convenient to have a function or procedure where the number of arguments is arbitrary.
This is done using the keyword ParamArray, followed by an array of variants.
Example:
 The following function computes an average of the numbers that are sent to it and returns the answer as
a single.
Function Average(ParamArray Number()) As Single
Dim Count As Integer, I As Integer
Dim Sum As Single
Count = UBound(Numbers) - LBound(Numbers) + 1
For I = LBound(Numbers) To UBound(Numbers)
Sum = Sum + Number(I)
Next I
Average = Sum / Count
End Function
 You can then call this function in code like the following:
YourAverage=Average (90, 100, 95, 80, 100)

THE NEW ARRAY-BASED STRING HANDLING FUNCTIONS


Explain about the new array-based string handling functions. (5 Marks)
Discuss about split function. (5 Marks)
79

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Discuss about filter function. (5 Marks)


 The Join function takes an array of strings and makes a new string out of all the entries.
Example:
Dim MyNieces(1 To 4)
MyNieces(1)=”Shara”
MyNieces(2)= ”Rebecca”
MyNieces(3)=”Alysa”
MyNieces(4)=”Deborah”
Simply write one line of code shown below to display all their names in a message box.
Msgbox Join(MyNieces) & “are the joy of my life.”
The Split Function:
 Suppose you have somebody’s full name, and you want to split it up into the three names:first, middle,
and last. Syntax: Split (expression [, delimiter [, count [, compare]]])
 The delimiter parameter is the string that marks the breaks. If you omit, VB simply assumes that you
want the string split at the space characters.
 The optional count parameter tells VB how many substrings you want in the array. Omitting it tells VB
to return all the substrings.
 The compare determines whether VB should be case sensitive if the delimiter is a letter.
 You can use either vbCompareText for a case-insensitive comparison or VbCompareBinary for a Case-
Sensitive comparison.
 This function can take this string and return an array of three strings:
 First array entry=”William”
 Second array entry=”Jefferson”
 Third array entry=”Clinton”
Example:
Private Sub Command1_Click()
Dim TestString As String
Dim A() As String
Dim I As Integer
TestString = "William Jefferson Clinton"
A = Split(TestString)
For I = LBound(A) To UBound(A)
MsgBox A(I)
Next I
End
End Sub
 The above code shows off the simplest form of the Split function, which involves breaking down a
string into the parts that are separated by individual spaces. However, it doesn’t work very well if the
user has inadvertently added multiple spaces.
 TestString = "William Jefferson Clinton"
 The easiest solution to the problem of multiple spaces is to simply use the Replace function to remove
extra spaces.
 A=Split(SuperTrim(TestString))
Example:
Public Function SuperTrim(TheString As Sting) As String
Dim Temp As String, DoubleSpaces As String
DoubleSpaces = Chr(32) & Chr(32)
Temp = Trim(TheString)
Temp = Replace(Temp, DoubleSpaces, Chr(32))
Do Until InStr(Temp, DoubleSpaces) = 0
Temp = Replace(Temp, DoubleSpaces, Chr(32))
Loop
SuperTrim = Temp
End Function
 The SuperTrim function allows us to replace multiple spaces by a single space.

80

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

The Full Power of the Split Function:


 You can tell Split function that backslashes mark the breaks. (whatever character you specify is called
the delimiter)
Example:
Private Sub Form_Load()
FileName = "C:\Window\Temp"
Dim A() As String
A = Split(FileName, "\")
For I = LBound(A) To UBound(A)
MsgBox A(I)
Next
End
End Sub
The Filter Function:
 This function takes an array of strings and returns a new array by including only those entries that
satisfy the filter or only those that do not.
 For example, suppose that an array named NamesOfNewsgroups contains the names of Internet
newsgroups.
 The Internet newsgroup names include dots-for example, rec.art.dance or comp.lang.basic.visual. The
first part of the name defines the hierarchy.if You want to filter out all the newsgroups in the alt
hierarchy. Use the following code:
 FilteredNewsgroups=Filter(NamesOfNewsgroups, “alt.”,False)
 In the above example, the new array eliminated entries that contained the search string. This was
controlled by the third parameter.
 If you change this parameter to True, you include the entries that contain the search string:
 CompNewsgroups=Filter(NewgroupNames, “comp.”, True)
 The full syntax of this function is
 Filter(inputStrings, value [, include[, compare]])
RECORDS (USER-DEFINED TYPES)
Explain about records (user-defined types). (5 Marks)
 A record is a type of “mixed” variable that you create as needed. It usually mixes different kinds of
numbers and strings.
 The first step is the Declarations section of a code module, enter
Type VitalInfo
Name As String
Salary As Long
SocSec As String
End Type
that defines the type. Now, to make a single variable of “type” VitalInfo, write either
Private YourName As VitalInfo (or) Public HisName As VitalInfo
in the Declarations section of any form or module. You can also write
Static MyName As VitalInfo
inside a procedure. Each of these statements sets up a single “mixed” variable.
 Now you use a dot(period) to isolate the parts of this record:
 YourName.Name=”Howard”
 YourName.Salary=100000
 YourName.SocSec=”036-78-9987”
 You can make up an array of records. For example,
 Dim CompanyRecord(1 To 75) As VitalInfo
 You can have records as one of the parameters in functions or subprograms.
Example:Private Sub AnalyzeSalary(X As VitalInfo)
This procedure allows that only variables of type VitalInfo be passed to it.
AnalyzeSalary (YourName)
 You also can pass individual components of a record whenever they match the type of the parameter.
You can also use arrays in user-defined records.
81

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

For Example:
Type RecordOfSalary
Salaries(1 To 12) As String
SalInPrevYear As Long
End Type
You can then use a loop plus one individual statement to fill a record rather than using 13 statements.
||***********************End of Unit –III***********************||
Text Book Referred:
2. “Visual basic 6 From the Ground up” by Gray Cornell

UNIT-IV
THE WITH STATEMENT
Explain about with statement. (5 Marks)
 The With Statement is used for quickly getting at the parts of a record.
Example:
With YourName
.Name=”Howard”
.Salary=100000
.SocSec=”036-78-9987”
End With
 You can even most With statements if one of the components of a record is itself a record:
Dim MyStats As ExpandVitalInfo
With MyStats
.Name=”Gary Cornell”
With .Salary
.SalInJan=1000
.SalInFeb=2000
.
.
End With
End With
 You can also use the With statement with properties of objects.
Example:
With txtBox
.Height=2000
.Width=2000
.Text=”This is a text box”
End With
 You can also nest Withs when dealing with objects or records.
Example:
With txtBox
.Height=2000
.Width=2000
.Text=”This is a text box”
With .Font
.Bold=True
.Size==18
End With
End With
ENUMS
Explain about ENUMS. (5 Marks)
 An enumerated data type is another user-defined type which provides a way for attaching names to
numbers, thereby increasing comprehensibility of the code.
 The enum keyword automatically enumerates a list of words by assigning them values 0, 1, 2, and so on.
One of the new features is called enumerated constants or Enums.
82

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 You place the definition of the Enum in the declaration section of the form or module.
Example:
Enum DaysOfTheWeek
Sunday=1
Tuesday
Wednesday
Thursday
Friday
Saturday
End Enum
 The visual basic automatically assigns successive integers to the days of the week (Monday=2,
Tuesday=3, and so on.)
Example:
If Weekday(Now) =Friday Then
MsgBox “Friday”
 After they have been defined, Enums can be used as the parameters for functions and procedures.
Example:
Function SalaryMultiplier(X As DaysOfTheWeek) as Single
Select Case X
Case Saturday, Sunday
SalaryMultiplier=1.5
Case Else
SalaryMultiplier=1.0
End Select
End Function
 Finally, you can also use Enums to create constants that do not follow any order,
Enum BonusLevel
NoBouns=0
StandardBonus=5
SpecialBonus=10
BossesBonus=100
End Enum
and use code like this,
Dim YourBonus As BounsLevel
YoursBonus=SpecialBonus
to give the YourBonus variable the value 10.

CONTROL ARRAYS
Explain about Control Arrays. (10 Marks)
 The user want to use the same control name more than once while designing a Visual Basic application
or use CTRL+C, CTRL+V to copy an existing control from one place on the form to another, Visual
Basic asks you whether you really want to create a control array by popping up the message box.
 When visual basic creates a control array, it gives the first control an Index property to zero, the second
control an Index property of 1, and so on.
 Like most properties of visual basic objects, you can change the Index property at design time using the
properties window.
Working with a Control Array:
 Suppose you want to work with the Change procedure for one of the two elements of the txtMoney
textbox control array.
 When you move to the Code window, by double-clicking one of these text boxes from the control array.
Instead of having no parameters, as the Change procedure ordinarily does, this event procedure now
uses a new parameter, Index As Integer.
 The index parameter is the key to the smooth functioning of control arrays.
Example:
Private Sub txtMoney_Change (Index As Integer)
83

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

If Index=0 Then
MsgBox “You typed in the text box with index 0”
Else
MsgBox “You typed in the text box with index 1”
End If
End Sub

 The above event procedure determines where you typed.


 Visual Basic simply adds an index as the first parameter to the parameter list for the given event
procedure in the Code Window.
Example:
The KeyPress event procedure for the control array of txtMoney textboxes now starts out as
Private Sub txtMoney_KeyPress(Index As Integer, KeyAscii As Integer)
instead of
Private Sub txtMoney_KeyPress(KeyAscii As Integer)
as it would for an ordinary text box.
Adding and Removing Controls in a Control Array:
 If you inadvertently add a control to a control array at design time, you can remove it by changing the
control name or deleting the control at design time.
JAIRAM ARTS & SCIENCE COLLEGE, SALEM-08
STAFF ID: SCS86 CLASS: III B.Com (CA) ‘A’
SUBJECT: SOFTWARE DEVELOPMENT WITH DATE:
VISUAL PROGRAMMING

(UNIT-IV Continued…)
The Load Statement: (Continuation… of Adding and Removing Controls in a Control Array)
 The Load method is used to controls while the application is running. The syntax for using Load is
pretty simple the txtMoney control array it would be.
 Load txtMoney(I)
Where, I will be the index of the element.
Private Sub Form_Load()
Dim I As Integer
For I = 2 To 5
Load txtMoney(I)
txtMoney(I).Text = "Text box #" + Str$(I)
MsgBox txtMoney(I).Text
Next I
End Sub

 If you run this program, you won’t see any of your new controls! Because whenever VB loads a new
element of a control array, the object is invisible-the Visible property of the new control is set to False.

84

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 You’ll need to change this to true, even if you do, there is another problem you’ll need to cure: all other
properties of your new control are copied from the object that has the lowest index in the array.
Private Sub Form_Load()
Dim I As Integer
For I = 2 To 5
Load txtMoney(I)
txtMoney(I).Text = "Text box #" + Str$(I)
txtMoney(I).Visible = True
MsgBox txtMoney(I).Text
Next I
End Sub
 You will only see the text box with index number 5. This is because the Left and Top properties start
out the same for all four of the newly created controls.
Private Sub Form_Load()
Dim I As Integer
Const SPACING = 10
txtmoney(0).Move 0, 0
txtmoney(0).Text = "Text Box in control array #0"
txtmoney(0).Width = TextWidth(" Text Box in control array #0 ")
txtmoney(1).Move 0, txtmoney(0).Top + txtmoney(0).Height + SPACING
txtmoney(1).Text = "Text Box in control array #1"
txtmoney(1).Width = TextWidth(" Text Box in control array #1 ")
For I = 2 To 5
Load txtmoney(I)
txtmoney(I).Text = "Text Box in control array #" + Str$(I)
txtmoney(I).Move 0, txtmoney(I - 1).Top + txtmoney(I - 1).Height + SPACING
txtmoney(I).Visible = True
Next I
End Sub

 In the above example the statement.


txtmoney(I).Move 0, txtmoney(I - 1).Top + txtmoney(I - 1).Height + SPACING
uses the position and height of the previous control to determine the position of the new control.
The Unload Statement:
 You use the Unload statement to remove any element of a control array that you added at run time via
the Load command. You cannot use the Unload statement to remove original elements of a control array
that were created at design time.
Example:
Private Sub Form_Click()
Static I As Integer
If I < 4 Then
Unload txtmoney(I + 2)

85

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

I=I+1
Else
Exit Sub
End If
End Sub
 If you try to load or unload a control array element twice in succession, Visual Basic gives a run-time
error.
LIST AND COMBO BOXES
Explain about list and combo boxes. (10 Marks)
 Use list boxes when you have a fixed list of choices. VB automatically adds vertical scroll bars
whenever the list box is too small for all the items it contains.
 On the other hand, you might want this application to let the user select a president by number rather
than by scrolling through the list, use a combo box.
 There are actually two types of combo boxes based on Style property.
o If the value of the Style property is set to the default value of 0, you get a combo box with an
arrow. If the user clicks the arrow, we will see the drop-down list of choices given in the box.
o If the value of the Style property of a combo box is 1, the user sees the combo box with the list
already dropped down.

 There are two kinds of list boxes, and working with the Style property.

 You can even change this property at runtime using one of the built-in constants vbListBoxStandard or
vbListBoxCheckBox.

Sorting Lists and Combo Boxes:


 Items in a list or combo box can be sorted in ASCII order by simply setting the Sorted property to be
True. If you set the Sorted property to false, the order of this item depends on the order in which you
placed them in the list box.
Manipulating the Items on a List or Combo Box:
 While the project is running, use the AddItem method to add an item to a list or combo box.
Syntax: ListName.AddItem Item[, Index]
 ListName is the control name of the list or combo box, and Item is a string or string expression. If the
Sorted property is True for the list or combo box, then Item goes where ANSII order places it. If the
86

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Sorted property is False, VB places Item either at the position determined by the Index parameter or at
the end of the list when you do not specify the index.
 The Index parameter must be an integer or integral expression. An Index value of 0 (not 1) means you
are at the beginning of the list. The Index option has no effect on where the item is added to the list if
the Sorted property of the list box is set to True.
Example:
Private Sub Form_Load()
List1.AddItem "George Washington"
List1.AddItem "Jonh Admas"
List1.AddItem "Thomas Jefferson"
End Sub
 You can also remove an item from a list while the program is running by using RemoveItem.
Syntax: ListName.RemoveItem Index
 ListName is the control name for the list or combo box and Index is the position where the item was
located.
 In addition to removing individual items on a list, you can use the Clear method to remove all the items
on the list.
 Syntax: ListName.Clear
Other Common List and Combo Box Properties:
 The Font properties determine which font is used to display the items in the list or combo box. The
BackColor and ForeColor properties control determine what colors are used for the background and
foreground.
 The Height, Left, Top and Width control determine the shape and location of the list or combo box.
Most Frequently used Properties:
List:
 This property is a Zero-based string array that contains all the items on the list. This gives you another
way to initialize the items in the list or combo box instead of doing it at run time.
 When you choose the List property in the Properties Window, VB opens up a list box where you can
type the items. You’ll need to place each item on a separate line, and this must be done by pressing
CTRL+ENTER and not the ENTER key between items.
List Count:
 This property gives you the number of items on the list.
Dim i
For i = 0 To List1.ListCount - 1
If List1.List(i) = "TheItem" Then
List1.RemoveItem i
Exit For
End If
Next i

List Index:
 The value of the ListIndex property gives the index number of the highlighted item. If no item was
selected, the value of this property is -1.
Example:
 Suppose you’ve stored information about the presidents in a string array named presidentinfo, which is
dimensioned as being from 1 to 42, and you need to get at the item in this array containing information
about the president that the user has selected from the list1 list box is achieved using the following code.
ReDim president(1 To 42)
president(1) = "George Washington"
president(2) = "John Adams"
A statement such as,
If ListIndex = -1 Then
MsgBox "No President Selected"
Else
info = president(List1.ListIndex + 1)
87

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

End If
Text:
 This is a property gives the currently selected item stores as a string. If lstBoxName is the name of the
list box, then the value of the lstBoxName. Text property for a list or combo box is the same as that of
lstBoxName.List (ListIndex) as long as only one item was selected.

Columns and MultiSelect:


 The Columns property controls the number of columns in a list box. If the value is 0, you get a normal
single-column list box with vertical scrolling. If the value is 1, you get a single-column list box with
horizontal scrolling. If the value is greater than 1, you allow multiple columns.
 The MulitSelect property controls whether the user can select more than one item from the list. The
following are the possibility values of this property.
Type of Selection Value How It Works
No Multiselection allowed 0 Allows multiple selection
Simple Multiselection 1 Use ordinary windows techniques and mouse dragging
SHIFT+ARROW key, CTRL+RIGHT ARROW to select more items.
List Box Events:
 List boxes respond to 12 events. The events are KeyUp, KeyDown, KeyPress, GotFocus, LostFocus,
Click, Double-Click etc.,
Combo Box Events:
 It responds to many of the same events as list boxes.
 The first event that is different is the Change event. The Change event occurs only for pull-down combo
boxes and simple combo boxes (Style=0 or 1).
 VB does not generate this event if you are using a pull-down list box (Style=2).
 VB generates this event whenever the user enters data in the text area of the combo box or when you
change the Text property of the combo box from code.
Associating Numbers with Items in List or Combo Boxes:
 Whenever you create a list or combo box, VB automatically creates a long integer array called the
ItemData array. This array is another property of the box.
 If you want to add the numeric data to an entry in this ItemData array, you need to know the array index
of the item. This is taken care of by the NewIndex property of the box. This property gives you the
index of the last item added to the box. To write the code to update the ItemData array.
 List1.AddItem "William Jefferson Clinton"
 List1.ItemData(List1.NewIndex) = 42
Adding What the User Enters to the Data in a Combo Box:
 The following code adds data into a combo box name cboBox during runtime, when the user loses the
focus after entered the data in the combo box.
Private Sub cboBox_LostFocus()
Dim NewItem As String
Dim I As Integer
With cboBox
NewItem = cboBox.Text
For I = 0 To .ListCount - 1
If .List(I) = NewItem Then
Exit Sub
End If
Next I
.AddItem NewItem
End With
End Sub
THE FLEX GRID CONTROL
Explain about flex grid control with example. (10 Marks)
Discuss about the general properties of the flex grid. (5 Marks)

88

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 The flex grid control lets you build spreadsheet-like features into your projects or display tabular
information neatly and efficiently. Moreover, the flex grid version works faster and uses fewer
Windows resources than a control array.
 This control displays a rectangular grid of rows and columns at design time. How many rows and
columns you see at design time depends both on the number of rows and columns you have set and the
current size of the grid.
 Each grid member is usually called a cell. Cells can hold text, bitmaps, or icons, and you can even have
some cells holding text and others holding graphics.
 Users can move from cell to cell by using the arrow keys or the mouse; VB handles such movement
automatically. As the user of your control moves around the grid, VB keeps track of what the current
cell is as the values of the Row and Col properties.
 Users can work with contiguous groups of cells in the grid, usually called regions, by clicking a cell and
dragging the mouse or by pressing SHIFT plus an arrow key to select the region.
General Properties of the Flex Grid Control
 The Height and Width properties tell you how large the grid will
appear. The Enabled property determines whether the grid will notice
keystrokes or mouse activity.
 If you set the ScrollBar property to a nonzero value, VB automatically
adds the appropriate scroll bars when there is information on the grid
that cannot be seen.
 The CellFontBold, CellFontItalic, CellBackColor, and CellForeColor
properties affect the text or color of the current cell.
Most Important Properties:
Cols, Rows:
 These properties determine the number of rows and columns in the grid. The default values for each of
these properties are 2, but you can reset them in code or via the Properties window, as needed. They
must be integers.
Syntax:
o GridName.Cols=NumOfCols%
o GridName.Rows=NumOfRows%
Example: .GridName.Cols=10
Col, Row:
 These properties set or return the row and column for the currently selected cell inside the grid. These
properties are only available at run time. The top left corner cell has Col value 0 and Row value 0.
ColPosition, RowPosition:
 These properties used let you move whole rows and columns around in your grid.
Syntax:
o GridName.ColPosition(number)[= value]
o GridName.RowPosition(number)[= value]
Example:
 The below code specifies every time they click in a cell, the column containing that cell moves to a
random location within the grid:
o Sub MSFlexGrid1_Click()
MSFlexGrid1.ColPosition (MSFlexGrid.MouseRow) =Int(Rnd*Rows)
End Sub
ColWidth, RowHeight:
 These two properties specify the width of a specific column or height of a specified row. They can only
be set via code. Both are measured in twips.
Syntax:
o GridName.ColWidth(ColNumber%)= Width
o GridName.RowHeight(RowNumber%)=Height
Text, TextMatrix:
 The Text property sets or returns the text inside the current cell. The TextMatrix properties set or
retrieve the text in an arbitrary cell without needing to change the Row and Col properties.
Syntax:
89

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

o TextMatrix(rowindex, colindex)=[string]

Example:
MSFlexGrid1.Cols=4
MSFlexGrid1.Rows=4
MSFlexGrid1.Col=3
MSFlexGrid1.Row=3
MSFlexGrid1.Text=”This would go in the bottom right corner”
MsgBox MSFlexGrid1.Text & “is in cell 3, 3”
MSFlexGrid1.Col=0
MSFlexGrid1.Row=0
MsgBox MSFlexGrid1.Text & “is in cell 0, 0”

CellLeft, CellWidth, CellTop, and CellHeight:


 These properties give you the size and location of a cell relative to its container.
ColAlignment:
 There are three possible settings for data inside a column. You can left-justify (value=0), right-justify
(value=1), or center the text (value=2).
Syntax: GridName.ColAlignment(Index%)=Setting%
FixedCols, FixedRows, and FixedAlignment:
 The Fixed rows and columns are always displayed in gray and must be at the top and left sides of the
grid. The default is that there is one fixed row and one fixed column. The FixedAlignment property
works exactly like the ColAlignment property but applies only to fixed columns.
Syntax:
o GridName.FixedCols=NumberOfFixedCols%
o GridName.FixedRows=NumberOfFixedRows%
o GridName.FixedAlignment=SettingNumber%
The setting for the alignment property has the possible values 0, 1, and 2.
GridLines, ScrollBars:
 These two properties control whether grid lines and scroll bars appear. The default is to show grid lines
and to have both horizontal and vertical scroll bars.
LeftCol, TopRow:
 These two properties control which are the leftmost column and highest row displayed from a grid. You
can these properties when the entire grid is too large to fit on the form. These properties can only be set
in code.
Example:
o GridName.LeftCol=LeftmostCol%
o GridName.TopRow=HighestRow%
Properties of Selected Cells inside Grids
 Although grids are often used passively to display data or pictures, it is even more common to make
them responsive to users. Users can select cells or regions and change their contents.
ColSel, RowSel:
 These properties work with the Row and Col properties to determine the size of the current selection. If
all four of these values are the same, the user has selected a single cell.
Example:
 The below code selects columns 0 through 4 and rows 0 through 3 (five columns and four rows).
o MSFlexGrid1.Row = 0 :MSFlexGrid1.Col = 0
o MSFlexGrid1.ColSel = 4 :MSFlexGrid1.RowSel = 3
Note:
 You must first set the Row and Col properties and then set the ColSel and RowSel properties in order to
define region in your grid.
Clip:
 This property sets or returns the contents of the selected region.
Syntax: GridName.Clip=String$

90

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 The string expression on the right-hand side contains the entire contents of the selected region. The
contents of each cell on the same row are separated from the adjacent cell by the tab character, and each
row is separated from the next by the carriage return character.
Example:
Private Sub Form_Load()
Dim S$
MSFlexGrid1.Rows = 3
MSFlexGrid1.Cols = 3
MSFlexGrid1.Row = 0 : MSFlexGrid1.Col = 0
MSFlexGrid1.ColSel = 2 : MSFlexGrid1.RowSel = 1
S$=Str$(1)+vbTab+Str$(2)+vbTab+Str$(4)
S$=S$+vbCr+Str$(4)+vbTab+Str$(5)+vbTab+Str$(6)
MSFlexGrid1.Clip=S$
End Sub
FillStyle:
 Sometimes you want what the user enters into one cell of the selected region to fill up the entire region.
You can control this by changing the FillStyle property from its default value of 0 to the value 1. In
addition, when FillStyle is 1, any image assigned with the Picture property automatically fills all cells in
the selected region.
HighLight:
 This has three values. The value 0 means that the user can’t tell when a cell is selected. The other two
values 1 and 2 give the user a visual clue.
AllowUserResizing:
 This determines whether the user can resize a row or column at run time using the mouse. The possible
values are:
Constant Value Description
flexResizeNone 0 The user can’t resize rows or columns.
flexResizeColumns 1 The user can resize columns.
flexResizeRows 2 The user can resize rows.
flexResizeBoth 3 The user can resize both rows and columns.

AllowBigSelection:
 This True/False property determines whether clicking on a column or row header selects the entire row
or column.
Sorting a Grid
 One of the most powerful features of the flex grid is its ability to sort rows according to the columns you
select. If you change the Sort property at design time, the grid stats out sorted. If you change it at run
time, VB sorts the rows of the grid immediately after it processes the statement.
Syntax: FlexGridName.Sort=Value
 The some of the possible values are:
Constant Value Description
flexSortNone 0 None
flexSortGenericAscending 1 Sort in ascending order
flexSortNumericAscending 3 Ascending but converts strings to numbers
flexSortStringAscending 7 Ascending but case-sensitive
Events and Methods for Grid Controls
 Grids respond too many of the standard events. The Click event determine whether the user clicked
inside the grid and the KeyPress event to send what a user is typing inside the grid directly to the
currently selected cell.
EnterCell, LeaveCell:
 EnterCell is triggered when the user clicks inside a cell that is different from the one currently selected.
LeaveCell is triggered right before the active cell changes to a new one.
RowColChange:
 This event is also triggered when the current cell changes. It occurs after LeaveCell and EnterCell.
91

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

SelChange:
 This event is activated when the selected region changes.
Methods for Resizing a Grid:
 There are also methods that let you insert or delete rows from a grid.
Syntax:
o GridName.AddItem Item$ [,Index%]
o GridName.RemoveItem Index%
The optional index parameter allows you to add the row at a specific location. The string given by Item$ is
placed in the first column of the new row; you separate successive items in the same row by tab characters
(vbTab)
CODE MODULES: GLOBAL PROCEDURES AND GLOBAL VARIABLES
Explain about code modules in detail. (10 Marks)
 When you start building larger projects with VB, you will probably want to reuse code as much as
possible. For this reason you will often want to store your procedures and functions in separate modules
rather than leaving them attaching to a form.
 A Standard (code) module is where you put code that you want to be accessible to all code in a project.
Standard modules have no visual components. They are also useful for reusing code. You add a new
Standard module by choosing Project | Add Module; you add an existing one to your project by
choosing Project | Add File. By convention, Standard modules have a .bas extension.
 The Sub and Function procedures in code modules are available to the whole project that is they have
global scope. This is because your placement of a procedure or of a declaration of a variable or constant
determines which parts of the project can use it.
 If you attach a procedure to a form, the procedure will default to being usable only by procedures
attached to the form. If you put the procedure in code module, the procedure will default to being
available to the whole project.
Example:
 Start up a new project with two forms and two command buttons. Name the button on Form1
cmdOnForm1 and name the button of Form2 cmdOnForm2. Change Private keyword to the Public
keyword in the cmdOnForm2_Click event procedure.
Public cmdOnForm2_Click ( )
MsgBox “This is the code in the now public click event attached to Form2”
End Sub
JAIRAM ARTS & SCIENCE COLLEGE, SALEM-08
STAFF ID: SCS86 CLASS: III B.Com (CA) ‘A’
SUBJECT: SOFTWARE DEVELOPMENT WITH DATE:
VISUAL PROGRAMMING

(UNIT-IV Continued…)
(Continuation… of Code modules: global procedures and global variables)
Public cmdOnForm1_Click ( )
Form2.Show
Form2.cmdOnForm2_Click
End Sub
 If you run this and click on the button on Form1, you’ll see the message box, proving that we accessed
the event procedure on Form2. If you went back and changed the Public keyword back to Private
keyword in the event procedure on Form2, you wouldn’t.
Public Variables:
 To make a variable attached to a form into a global variable to every part of a project, use a statement of
the form.
Public VariableName As VariableType
 Then somebody can see that variable by using FormName.NameOfVariable. The Public identifier on
variables or procedures attached to a code module, you don’t need to use the name of the code module.
Example:
o If you added the following line to the Declarations section of any code module named
MyCode.bas
92

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Public gInterestRate As Single


o then every bit of code in your project can see the variable named gInterestRate simply by using
the name gInterestRate.
 To save the code module, open the File menu and choose Save Module As and then type the name of
the module. Finally, you can have as many code modules as you want in a project. To open a specific
code module window for any code module in the current project, double-click on the name of the
module in the Project Explorer, or use the Object Browser.
Fine Points about the Scope of Procedures
 Code modules can also have module-level
variables that are visible only to the code
attached to that module. To make a variable a
global variable requires the Public (or Global)
keyword or access modifiers, because they
control what code can see (access) the code so
identified.
 If you use the ordinary Private (Dim)
declaration syntax that you have been using for
code attached to a form in the Declarations
section of a code module, then the variable is
visible only to the procedures attached to that
code module. Similarly, if you use the Private (Dim) statement inside a procedure attached to a code
module, that variable is local to the procedure.
 When you use a Sub or Function procedure inside another procedure, VB follows these steps to
determine whether to look for it:
o VB first looks at procedures attached to the current form or module.
o If the procedure is not found in the current form or module, VB looks at all code modules
attached to the project.
Adding or Removing Existing Code Modules
 To add an existing code module, open the Project menu and choose the Add Module option. Choose the
Existing tab on the dialog box that opens; this gives you a standard File open dialog box asking for the
name of the file.
 To add code from another file to an existing module, choose Insert | File and then work with the dialog
box that pops up.
 To remove a code or form module from a project. Follow these steps:
 Open the Project Explorer window by clicking on any part that’s visible or choosing View |
Project Explorer.
 Select the code module or form module you want to remove.
 Either choose Remove from the right-click menu, or choose the Remove item from the Project
menu.
THE DOEVENTS FUNCTION AND SUB MAIN
Explain about DoEvents function. (5 Marks)
 Windows operating system gives each program a “slice” of time to work before giving the next program
a change.On the other hand you can foul up your own program by preventing Windows from sending
information about events that happened to the running program. To see this at work, start up a new
project and add the following code to the Form_Load:
Private Sub Form_Load()
Show
Do ‘an infinite loop
‘nothing being done
Loop
End Sub
 If you run this program, you’ll see that clicking on the Exit button doesn’t end the program-it doesn’t
even close the form because of tight/infinite loop. The solution to this problem is achieved using
DoEvents. Windows maintains a list of pending events in what is called an Event Queue. The DoEvents

93

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

statement passes control to Windows, and VB gets control back only the operating system has finished
processing the events in its queue. Thus, if you changed the above code to read.
Private Sub Form_Load()
Show
Do ‘an infinite loop
DoEvents
Loop
End Sub
 The form will close normally when you click on the Exit button. Tight loops are tricky-even DoEvents
is not a cure-all! So you can simply put an End statement in the Query_Unload event of that form in
order to end this program naturally.
ACCESSING WINDOWS FUNCTIONS
How can we access the windows functions? (5 Marks)
 Windows itself can be thought of an interlocking set of DLLs containing hundreds of specialized
functions. These are called Application Programming Interface (API) functions. Some tasks, such as
learning whether users have swapped their mouse buttons or putting a window always on top, or
checking or setting the state of the keyboard, must be done with an API function. You can even use an
API function to reboot a user’s computer and start a program when windows reboots.
 API statement requires a special type of declaration called Declaration statements. There are two
possibilities for the general form of the Declare statement. For a sub program in a DLL use.
o [Public | Private ] Declare Sub name Lib “libname” [Alias “aliasname”][([arglist])]
 For a function use
o [Public | Private ] Declare Function name Lib “libname” [Alias “aliasname”][([arglist])]
[As Type]
 The Lib keyword tells VB that a DLL is being called. The libname argument is the name of the DLL
that contains the procedure you will be calling. The Alias keyword is used when the procedure has
another name in the DLL but you don’t use it.
 The Declare statement for the Window API version of the Beep function look like this:
o Declare Function APIBeep Lib “kernel32” Alias “Beep” (ByVal dwFreq As Long, ByVal
dwDuration As Long) As Long
the dwFreq parameter gives the frequency of the beep, and the dwDuration parameter gives the duration
in milliseconds.
ERROR TRAPPING
Explain about error trapping. (5 Marks)
 The command that activates (enables) error trapping within a given procedure is
o On Error GoTo…
Where, the three dots stand for the label that defines the error trap. The labeled code must be in the
current procedure. You cannot jump out of a procedure using an On Error GoTo command. A label is
any identifier ending with a colon that satisfies the rules for variables.
o ErrorTrap:
‘Error code goes here
 Usually, the error-trapping code is inside that procedure. When one procedure has been called by
another VB will look to see if an error trap was enabled in the earlier procedure if one does not exist in
the second procedure.
 The On Error GoTo command should transfer control to a piece of code that identifies the problem and,
if possible, fix it.
 If the error can be corrected, the Resume statement takes you back to the statement that caused the error
in the first place. However, you can’t correct an error if you don’t know why it happened. You identify
the problem by means of either the Err function of the Err object. This gives you an integer that you can
assign to a variable. For example if you write.
o ErrorNumber=Err.Number
 The value of the variable ErrorNumber is the error number. Visual Basic can identify more than 80 run-
time errors. Examples:

94

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 Suppose an event procedure will be using the printer. Somewhere in the procedure, before the error can
occur, place a statement such as this:
o On Error GoTo PrinterCheck
Now, before the End Sub, add code looks like this:
Exit Sub
PrinterCheck:
ErrorNumber=Err.Number
Beep
Select Case ErrorNumber
Case 57
MsgBox “Your printer may be offline”
Case 68
MsgBox “Is there a printer available?”
Case Else
MsgBox “Error with” & ErrorNumber & “occurred”
End
End Select
More on Error Code Explanation
the 57 Device I/O error (for example, trying to print when the printer is offline)
Resume 68 Device unavailable (the device may not exist or is currently unavailable.
482 A general printer Error
Statement:
 A variant on the Resume statement lets you bypass the statement that may have caused the problem. If
you use Resume Next VB begins processing at the statement following the one that caused the error.
You can even use On Error Resume Next to automatically bypass any code that causes an error.
 You can also resume execution at any line of code that has been previously identified with a label. For
this, use Resume Label.
 Both the Resume and Resume Next statements behave differently that is for the Resume statement, VB
will call the original procedure again. For the Resume Next command, VB will execute the statement
after the call to the original procedure. You will never get back to the original procedure.
The Erl (Error Line) Function:
 Erl is one of the error handling function used to find the line that caused the error.
Disabling Error Trapping:
 If you are confident that you will no longer need an error trap, you can disable error trapping with the
statement On Error GoTo 0
More on the Err Object:
 VB provides the special Err object, which can be analyzed when an error occurs. Number property of
the Err object (Err.Number) gives you the error number.
 The Err.Description gives a understandable description of the error. The Err.Source gives you the source
of the error if you are accessing another Windows application through OLE.
 All the Err objects properties are reset to 0 after VB processes either a Resume or a new On Error
Statement. You can also use Err.Clear to reset the Err objects properties. If you want to generate an
error for testing purposes, use the Raise method of the Err object. Its syntax is Err.Raise(Number).
CREATING AN OBJECT IN VISUAL BASIC
How can we create an object in VB. (5 Marks)
 You can build objects in three ways in VB. One is by adding custom properties to an existing form and
then using that form as a class (template) for new instances of the form. Each new instance of the form
will have the new properties.
 The second way is by using a special type of module called a class module.

95

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 Class modules have the advantage that they can be compiled separately and used by other Windows
applications-even other VB program.
 The third alternative is to create a custom control. In all three cases you start with same ideas for adding
properties to these classes (templates). First off, what are the most basic things you will want to be able
to do with a new property?
o You want to get its current value.
o You want to assign a new value to it.
 For the first situation, you use a special type of procedure called a Property Get procedure. For the
second, you use a Property Let procedure. If the value you are assigning is itself an object, you use a
Property Set rather than a Property Let.
Example:
 Suppose you want to add a custom property to a form that will tell you whether a form named
frmNeedsToBeCentered is centered, and also to center it if you set the property to True. Set up a Private
variable in the declarations section of the form.
o Private IsCentered As Boolean
 Then add the following procedures to the form:
Public Property Let Center(x As Boolean)
IsCentered=x
If x Then
Me.Move(Screen.Width-Me.Width)/2,Screen.Height-Me.Height)/2
End If
End Sub
 The first line of code uses the Private variable to store the current value of the property. Use the
following code.
o Me.Center=True
to center the form. From another form or code module, you can use a line of code like this:
o frmNeedsToBeCentered.Center=True
It might also be useful to know whether a form is centered. For this you need to use a Property Get
procedure that returns a Boolean:
Public Property Get Center() As Boolean
Center=IsCentered
End Sub
This picks up the current value of the IsCentered Private variable that you are using to hold the
information about the current value of the property.
Sub Form_Load ()
If Me.Left=(Screen.Width-Me.Width)/2 And Me.Height=Screen.Height-Me.Height)/2 Then
IsCentered=True
End If
End Sub
JAIRAM ARTS & SCIENCE COLLEGE, SALEM-08
STAFF ID: SCS86 CLASS: III B.Com (CA) ‘A’
SUBJECT: SOFTWARE DEVELOPMENT WITH DATE:
VISUAL PROGRAMMING

(Unit –IV Continued…)


(Continuation of creating an object in visual basic…)
General Property Procedures
 The value returned by the Property Get procedure is of the same type as the one used in the assignment
for Property Let. The number of arguments for a Property Get is also one less than that of the
corresponding Property Let.
 A Property Get procedure that you write without a corresponding Property Let procedure gives you a
read-only property. The name and type of each argument in a Property Get procedure must be the same
as the corresponding arguments in the corresponding Property Let procedure-if it exists. The type of the
value returned by a Property Get procedure must be the same data type as the last argument in the
corresponding Property Let procedure, if it exists.

96

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 The syntax for the Property Let procedure template look like this:
[Public | Private] [Static] Property Let name [(arglist)]
[Statements]
[name=expression]
[Exit Property]
End Property
 Use Public to make the Property Let procedure accessible to every procedure in every module. Use
Private to make the Property Let procedure accessible only to other procedures in the module where it is
declared.
 Use the Static keyword if you need the Property Let procedure’s local variables preserved between uses.
The Exit Property keywords give you a way to immediately exit from a Property Let procedure. The
name of the Property Let procedure must follow standard variable-naming conventions, except that the
name can, and most often will, be the same as a Property Get or Property Set procedure in the same
module. The usual syntax for a Property Get procedure template looks like this:
[Public | Private] [Static] Property Get name [(arglist)] [As type]
[Statements]
[Name=expression]
[Exit Property]
End Property
 The last type of Property procedure is the Property Set statement. Use this when you need to set a
reference to an object instead of just setting a value.
[Public | Private] [Static] Property Set name [(arglist)]
[Statements]
[Exit Property]
[Statements]
End Property
 If you choose Tools | Add Procedure and choose “property” type, VB automatically gives you the
following templates:
Public Property Get ExampleProperty () As Variant
End Property
BUILDING YOUR OWN CLASSES
How can we build your own classes? (5 Marks)
 The most common way to build a new class (template) for new objects in VB is to use a class module. A
class module object contains the code for the custom properties and methods that objects defined form it
will have. You can then create new instances of the class from any other module or form in your project.
A class module cannot have a visible interface of its own. Each class module you create gives you,
naturally enough, a single class (template) for building new instances of that class. However, you can
have as many class modules in a project as you like.
 Once you have a class module, you use the New keyword to create new instances of it. For example, if
FirstClass is the name of a class module in your project, you would create an instance as follows:
o Dim AnInstance As New FirstClass
 You use Property procedures to define the properties of your class and use Public Sub and Public
Function procedures for its methods.
Creating a New Class Module:
 You create a new class module at design time by choosing Project| Add Class Module. Each class
module can respond to only two events: Initialize and Terminate. They are triggered when someone
creates an instance of your class or terminates it.
||***********************End of Unit –IV***********************||
Text Book Referred:
3. “Visual basic 6 From the Ground up” by Gray Cornell

UNIT-V
CRYSTAL AND DATA REPORTS
CRYSTAL REPORTS

97

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Write Short notes on crystal reports. (5 Marks)


What are the Prerequisites for working with crystal reports? (5 Marks)
Write down the steps involved in creating a report through a wizard. (10 Marks)
Write down the steps involved in creating a report without wizard. (10 Marks)
Write Short notes design/preview window. (5 Marks)
Explain the process of calling crystal reports from visual basic. (5 Marks)
 In VB the development of the Invoicing program focuses on controls, tables, databases and the code what
we have not worked on so far is the Reports. The user of our application would definitely want to know a
number of details about the state and status of his business.
 For example the total number of items sold in a day, week, or month. Or the list of items supplied by a
Supplier for a given month. Or the payments due with amount and date. A businessman will need to know
a lot more than this.
 Our application must provide the means for him to get the all the information possible based on the data
provided to the application.
 We can build this functionality into our application with the help of VBA code or through report
generators like Crystal Reports or Data Report.
 Crystal Reports is a third party product developed by Seagate of Singapore. It has been bundled with
various data access tools. It can work with Visual Basic on your PC or with the AS/400 as well.
Prerequisites for working with Crystal reports
 Hardware: A printer must be installed. It need not be physically connected though. This is because
Crystal Reports builds the reports based on the properties of the printer.
 Application: You can access Crystal Reports only through the VB IDE. If Crystal reports have not
been installed then follow the steps given below. Prepare a pencil copy of the report structure that
you want to create.
 Installation: So, Crystal Reports has been installed and you have a rough copy' of the report that you
want. Let us get started. Click on Add-Ins. Select Report Designer. (For some reason best known to
Microsoft, Crystal Reports is not mentioned by its original name.) You will see the following figure.
If you have not registered your name so far do so now.

Click on Field and Select New. Or click on the icon (in picture) that represents a new report.

 You will see the following figure.

98

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Creating a Report through a Wizard


 You are presented with the Create New Report Wizard that will allow you to create new reports. You
can choose the report style. For this exercise, click on Standard.
 The wizard will now take you through a number of steps asking you for details. Supply the details to the
best of your knowledge. If even you make an error the reports can be corrected later.
 Remember that right from the first step you are given an option to preview the report that you are
creating. Avoid the temptation to see the report. Once you do that you cannot come back to the wizard.
 If you wish to return to the wizard, you will have to start all over again. We will see the various steps
required to create a Standard Report and then call the 'Expert' for a particular step.
 The wizard in the dialog box will ask you to select the database(s) that you will be using to generate the
report. Let us select Nwind.mdb for a change. (You will be generating your own reports using the
Invoice.mdb).
 Upon selecting the Nwind.mdb, all the tables and stored queries/view will get added to the ListBox.
After you have added all the databases that you want to work on click on 'Done'. You will see the
following figure.

 This figure will display the various tables and the relationship between each of them. If you think there
are too many tables and views and you do not need all of them, then you can delete some of them.

 Click on the button 'Back'. You will see the following figure.

99

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 You can select the items that you do not need and click on remove to remove them one by one. When
you are sure you have only those tables that you need click Next to continue. You will see the figure
with the selected tables and their relationship. Click Next to continue. You will see the following figure.

 In this dialog box you can add the fields that you wish to include in your report the fields that you select
here will appear on the report. However the selection criteria for the selected records need not depend on
these fields alone. When you have selected the fields and added them one by one in the 'Report fields'
ListBox. Click on Next to continue. You will see the following figure.

100

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 In this dialog box you can choose the fields on which the report is to be sorted out. For example, you
can sort all the details based on the City, or the Product that a customer uses, or the Turnover of the
company, etc. Select the fields on which the criteria is to be built and then select the sort order.
 For example, you can sort the details in the ascending order or descending order. When you are through
with this click Next to continue. You will see the following figure.

 In this dialog box you must select the fields on which you have to perform calculations like group total,
sub-total, etc. For example if you want to know the number of customers in a particular city, then select
Customer_City and add it to the "Total Fields' ListBox. Here you can also choose if you want to total
the number of customers for a city or if you want to the add the figures for a particular column. For our
example choose Count. Then Click next to continue. You will see the following figure.

 In this dialog box you must choose the fields based on which the records must be selected from the
database. In the Report Fields ListBox you are presented with the fields that you have selected for the
report. If none of these fields meet your requirements to determine the selection criteria, you can scroll
down further and select from the fields that have not been included in the report. Build your selection
criteria and click Next to continue. You will see the following figure.

101

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 In this dialog box you can select the layout of the report. Select the report layout style that you think
suits you best. The selection of the style will depend upon the type of data that you are likely to have on
the report.
 For example, if you are going to have the total amount out-standing from a customer and your report
will hold the status of customer for a city or area then you can choose Trailing Break Style or the Drop
Table style. It’s suggested that you preview the various types of reports possible before settling for a
particular style.
 Next you can preview the report. The preview of the report will look like this

 So we have created a report from scratch with the help of a Wizard or and Expert. Let us see how we
can create a report without the help of a Wizard. Remember that the steps required to create a report will
be more or less the same.

102

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Creating a Report without a Wizard


 Let us create a sample database file with two tables for this exercise. The name of the .mdb file can be
any name of your choice (follow the naming conventions). We will call it Test.mdb.
 We will work with two tables. The Customer_Data and the Order_Data tables. (In case you do not
have such a database file with such tables create them for the sake of this exercise).
 The Customer_Data table has these fields
Customer_Code
Customer_Name
Customer_City
 The Customer_Data table is indexed on Customer_Code as the primary index.
The Order_Data table has these fields,
Order_ID
Customer_ID
Order_Value
Order_Date
 The Order_Data table is indexed on Order_ID as the primary index and Customer_Code the
secondary index.
 Click on the New File icon or select New from the File Menu. You will see the figure that we saw in the
last session. Instead of selecting standard, click on 'Custom'. An extended set of buttons will be
displayed.

 From the extended set of buttons displayed select Custom and then click on the Data File button.
 You will be asked to select the database file. Select Test.mdb in order to complete this example. (In
case you do not have such a database file with such tables create them for the sake of this exercise).
 Next you will see a figure like one as shown in the next page.

103

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 This is called the Design/Preview window. Here you can design and view the report as you go on
adding fields to it.
The Design/Preview Window
 This is the window where you design your reports. The default tab is the Design tab. This window is
divided into two parts. The Large white area is where you actually insert the fields are the gray area on
the left side with several rows.
 The rows will be titled as Title, Page Header, Details, Page Footer and Summary. Each of these titles is
separated by a line ha extends into the large white area. This is to help you correctly insert and correct
the data that should appear on the report.
 If you click on the Preview tab, a preview of the report will be displayed. You can zoom to get a letter
view of the report. The button to zoom is
 In the figure above, the Insert Data Field dialog box displayed over the design window consists of the
list of fields that you can display on the report. Apart from the list box there are three buttons "Insert",
"Done" and "Browse Field Data".
 To insert a field select it and push the Insert button. Your mouse pointer will suddenly acquire a square
tail. This is tells you that you were selected a field and you can insert it at a location on the report.
 Move the pointer to the location where you wish to display the selected field and click on the muse. The
field will get inserted at that location.
 Let Us get back to the Insert Data Yield Dialog box. Select Customer_Name from the list of fields
displayed in the ListBox. Click on the 'Insert' button.
 Notice that your mouse pointer has acquired a 'tail’. Move the mouse pointer to the section 'Details' on
the 'White Area' and click the left mouse button.
 The Customer Name field gets placed there along with the heading. You can change the column heading
later if you do not like the current heading. Similarly add two more columns namely Order_Date and
Order_Value to the report.
 Click on the Preview tab to view the report. You will see a list of the customers with the Order Date and
Order Value. Some of the problems with this report are:
1. The customer names are repeated.
2. There are no sub-totals for individual customers.
3. There is no grand total of the Order Value.
 Let us see how we can correct them. We are at liberty to call on the 'experts' for help. We will first sort
the listing on Customer_Name. Click on the 'Reports' Menu Option. From the menu items select 'Sort
Records'. You will see the following dialog box.

104

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 From the list of items in the Report Fields ListBox on the left add the Customer_Name to the Sort
Fields ListBox on the right. Select the Ascending (default) order for sorting the records.
 Now Click the Preview tab to see the result. To avoid repeating the Customer_Name (or for that matter
any field) for every occurrence, click on Format. From the menu click on 'Fields'. You will see the
following dialog box.

JAIRAM ARTS & SCIENCE COLLEGE, SALEM-08


STAFF ID: SCS86 CLASS: III B.Com (CA) ‘A’
SUBJECT: SOFTWARE DEVELOPMENT WITH DATE:
VISUAL PROGRAMMING

(Unit –V Continued…)
(Continuation the Design/Preview Window…)
 Click on the ‘Suppress if Repeated' option button, to include Sub-Totals for the Order_Value for each
customer, right click the mouse on the Order_Value in the Details section. From the pop-up menu
select_Insert Sub-Totals. You will see the following dialog box.

105

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 The message displayed will be "When the report is printed the records will be sorted and grouped by"
Next to this message is a drop-down combo box. Click on the down arrow to view the list of fields that
you can group by. Select Customer_Data Customer Name. A message will appear at the bottom of the
dialog box. "The subtotals will be printed on any change of Customer_Data.Customer_Name".
 Click OK to accept the changes. To add the Grand Total to represent the total of all Order_Values,
once again right click the mouse on the Order_Value in the Details section. From the pop-up menu
select 'Insert Grand Total'. You will see the following dialog box.

 Select 'Sum' from the drop-down ComboBox. You have a wide choice of options to choose from for the
Grand Totals column.
 Now preview your report. Your report should look like this.

 Save the report in your directory. It will have an extension name ".rpt"
Calling Crystal reports from Visual Basic
 So you have learnt how to create a report using Crystal Reports. We need to be able to call the report
that we have created from our application. In order to be able to call Crystal Reports from our program
we must first add the Crystal Reports control to our program.
 Start a new project. The Crystal Reports control should be added to the form from where you intend to
call the report.
 You will not find the control on your toolbox, to add it to your toolbox right click the mouse on the
toolbox and select Components from the pop-up menu. From the list of components select Crystal
Reports Control 4.6.
106

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 Add an instance of the Crystal Reports control on your form. Since this control is not visible during
runtime it will appear as an icon at design time. Right Click on the icon and select
Crystal Properties from the menu.
 The most important property to set here is the ReportFileName. This is set in the General Tab. Set it to
the filename under which you saved your report. Under this tab you can also specify if your report
should go to the printer or to the window or to a file.
 Add a CommandButton to your form. In the click event of the CommandButton add the following line
of code.
CrystalReportl. Action = 1
 If you are going to use more than one report file in your program then you need to set the
ReportFileName before you run the report.
 You see the ReportFileName as follows
CrystalReportl. ReportFileName = "C:\azam\vb-exersices\crysl.rpt"
CrystalReportl. Action = 1
 Most of the properties that you see in the Property pages are available at runtime and can be modified
when needed. You can for example use a selection formula to select the records that appear on the
report.
 If you want the report to display selected records, for example you want to see details of the customer
whose Customer_Code is C455 then add the following line in the SelectionFormula ListBox under the
Selection Tab.
{CustomerJData.Customer_Code} = "C455"
 Run the program and you will see the details of customer C455 only.
DATA REPORTS
Write short note on data reports. (5 Marks)
Explain about data report designer. (5 Marks)
Write short note on various parts of a data reports. (5 Marks)
Explain about various sections of a Data Report designer. (5 Marks)
Write notes on Data Report Controls. (5 Marks)
Write notes on extracting the Data. (5 Marks)
 In the last session we saw how to use Crystal Reports to create reports. In the following session we
will take a look at Data Report. Data Report is the new offering from Microsoft perhaps with a view
to replacing Crystal Reports in the long run.
 Data Report as it stands today is meant for programmers. A general user of computers will not be
able to get around it. Let us take a look at what Data report has to offer and how we go about using
this toolIn order to use Data Report you need to use ADO or Data Environment. Since we have
covered ADO in the previous chapter we will work using ADO with Data Report.
 You need to follow the following steps to generate a report using the Data Report.
1. Create a data source usingADO.
2. Add the Data Report object to your project.
3. Place texboxes representing the various fields that you want on the DataReport object.
4. Link the Textboxes to the various fields of the data source
5. Display the report using the Show method.
 This sounds like quite a bit of work. Actually it is quite easy if you have already worked with the
Data Control or the ADO Data Control.
 The approach is very similar and you will find it fairly simple unless you are a die-hard fan of Crystal
Reports.
Getting Acquainted With the Data Report Designer
 Data Report Designer is not part of your toolbox. To add it to your toolbox, right click on the toolbox
and select Components from the pop-up menu. On the Component dialog box, click on the
‘Designers' tab and select 'DataReport'. Close this dialog box.
 Let us take a look at the DataReport object. This will give us an idea about the approach to be taken
for generating a report.
 The Data Report Designer is the form on which you design the layout of the report. The DataReport
object is the programmable object that represents the Data Report Designer.

107

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 Click on 'Projects' In this menu you will see a new item 'Add Data Report'. Select this item to add a
Data Report Designer to your IDE. Please remember that this designer will not be placed on your
form. The Data Report Designer is a separate form by itself. Open the Project Explorer and you will
see another item called DataReportl along with the Forml. Also notice that your toolbox has acquired
a tab called Data Report with its own set of tools.

Parts of the Data Report


 The Data Report consists of three main components.
1. Data Report object
2. Section object
3. Data Report Controls
 You need a form or the area where you arrange the various fields that you want to display. This is the
Visual Designer component of the DataReport object. The designer component can be controlled
programmatically using the DataReport object.
 The Data Report Designer consists of a number of Sections like the header, footer, and details sections.
Each of these Section objects can be configured at design time or controlled through code at run time.
Each section has a set of properties that can be manipulated.
 Finally you have the Data Report controls, which are special control that you can create on the Data
Report designer. These tools are placed under a separate tab on your toolbox.
The default Data Report designer contains these Sections:
 Report Header: You give the title of the report in this section. If the first page of the report should
contain only the title, then set its ForcePageBreak property to rptPageBreakAfter.
108

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 Page Header: You give the page heading here.


 Group Header/Footer: you give the heading for every group here. For example your report can contain
details of Customer for each city here. So the Group Header can be the name of the city. A group header
must also have a Group Footer.
 Details: This section contains the actual data. The records are displayed in this section.
 Page Footer: You give the page footer here.This can be the page number or any relevant text like the
date of report, etc.
 Report Footer: You give the summary for the report in this section. This can contain the address, the
bibliography, contact address, etc. The Report Footer appears between the last Page Header and Page
Footer.
Data Report Controls
 Following are the new set of controls that are placed under the Data report tab on your toolbox.
 TextBox Control (RptTextBox) — Tb display text or other formatted data.
 Label Control (RptLabel) —To display the labels on the report to identify fields or sections.
 Image Control (Rptlmage) —To display pictures on the report. This control cannot be tied to a data
field.
 Line Control (RptLine) —To draw lines on the report.
 Shape Control (RptShape) — Tb draw rectangles, circles, etc on the report.
 Function Control (RptFunction) —This is a special text box that calculates values as the report is
generated.
Extracting the Data
 We saw earlier in this session that we must first create a data source using ADO. Let us do that aow.
We will use our Invoice.mdb. Let us create a list that consists of Customer_Name, Customer_City and
Order_Value. We need to work with two tables
Dim adocon As ADODB.Connection
Dim adors As ADODB.Recordset
 In the above code fragment we have declared an ADO connection and an ADO Recordset object.
 In the Form load event add code to create the connection and then to create a recordset. The following
lines of code will do the trick
Set adocon = New ADODB.Connection
adocon.Open "DSN-Invoice"
 In the form load event itself you can populate the recordset. But this is not such a good idea. If you are
not going to view/display the report then the recorset is unnecessarily taking up memory. In order to
avoid this add a button to your form.
 Let the caption be "Display". In the code window of this CommandButton, enter the following code.
Set adors = adocon.Execute("Select distinctrow Customer_data.customer_name,
Customer_data.address2, orders_data.ordervalue from Customer_data,orders.data where
Customer_data.cu8tomer_code = orders_data.customercode")
 The above code segment will populate the Recordset.
 We now have data readily available.
 The Recordset will have all the fields from both the tables. Next we have to display the fields that the
user is supposed to view.
Working with the Data Report
 In the details section of the Data Report designer, add three of the RptTextBox controls. Notice that it is
just like adding ordinary textbox controls.
 Also observe that these textboxes contain a caption called 'Unbound'. This means that these RptTextBox
controls are not bound to any data source or data field.
 Binding the RptTfextBox to a data field: Bring up the Properties window of the RptTextBox by
pressing F4.
 Enter the name of the field that you want to display against the Data Field property.
 For our example, the three RptTextBox controls will display the "Customer Name", "Customer City",
"OrderValue". Enter these field names as they are in the database.
 If they are wrongly spelt you will get an error message.
Displaying the report

109

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 We are now ready to display the data. We have created the recordset. We have assigned the fields in
the Data Report Designer.
 We need to link the recordsource to the Data Report. Then we must caU the Show method of the Data
Report. The following lines have to be added to the "Display" command button.
Set DataReportl .DataSource = adors
DataReportl.Show
 Run the program now.

 Add headers to the report using the RptLableBox controls so that the report looks meaningful.
CREATING MULTIPLE REPORTS
Explain how to create multiple reports. (10 Marks)
 The users of your application are not going to be happy with just one report. They will want the data
presented in many and every combination. We can cater to this as well. There are two ways of
handling the 'multiple reports' situation.
 For every report that the user wants, we can create a DataReport or we can display different data using
only one or a few DataReport forms. Both the approaches have their merits and demerits.
 We have already created one report using one DataReport. Creating more reports using the same
method should not be very difficult.
 However displaying more than one report using only one DataReport involves a little work.
 Details like Caption, Page Headers, Footers, etc. for each of the reports must be determined. The
heading for the data must also be determined. The data and the source of the data must also be worked
out.
 Depending upon the number of reports that you may need to display on form, you have to work out if
it is feasible to create a recordset or a number of recordsets for all the reports. Creating a recordset
every time the user asks for a report may not be a good idea especially in a multi-user environment.
 At the same time creating a large number of recordsets and locking up resources will not be the right
thing to do.
ACTIVEX: OBJECTIVES
What is the reason behind the creation of ActiveX? (5 Marks)
What is ActiveX? (2 Marks)
Write short notes on OLE. (5 Marks)
How will you Registering an ActiveX Control. (2 Marks)
 The primary purpose of this chapter is to demystify ActiveX. In this chapter we will discuss the
following:
1. What is ActiveX?
2. DDE and OLE, the technologies before ActiveX
3. What is an ActiveX Control?
4. Creating an ActiveX Control
5. Writing the code, adding properties
6. Registering the ActiveX Control.
What is ActiveX?

110

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 It can be described as an ingredient that will add energy to your document. It can be described as a shot
in the arm for a programmer.
 A cocktail, a mix of marketing hype and programming evolution. A health drink like Milo or Horlicks.
 By the time you have gone through the following pages, you will be able to decide on a particular
definition, or you may even create your own definition. After all, that is what ActiveX is all about.
Why ActiveX?
 The concept of ActiveX was developed for very simple reasons:
 To be able to import data from one application to another.
 To be able to make changes in the imported data such that the data in the parent application was
also updated.
 To be able to place different types of data or 'objects' in one document.
 The first technology was DDE or Dynamic Data Exchange.
 This technology allowed applications to exchange data.
 It also allowed one application to send commands to the other application.
 This technology was not very successful, and gave way to newer technology.
 Next came OLE, an acronym for Object Linking and Embedding.
 Under this technology, one document could display an object from different applications.
 As the name suggests, the imported object would get 'embedded' in the host document.
 By clicking on an object in the document, the parent application of that object would get
invoked.
 The advantage of this technology was that no conversion of data was done from one application
to another.
 Let us take a break and discuss another point.
 Programmers who work in the C language are very fond of using the term 'function'.
 Systems Analysts are very fond of using the term 'reusable functions'.
 The top brass in a development set-up likes to talk of ‘reusable code'.
 However, all this to a large extent has remained only TALK.
 This is because a function can be used or reused only in that program.
 Reusable code is limited only to that language.
 Therefore programmers came up with libraries where functions would be available for use by
any program.
 However, this too had the limitation of the language.
 Then came DLLs.
 DLLs suffered from version problems. If the date (and camels) did not match, the program would not
work. Take a Visual Basic application from one machine to another to experience first-hand the agony
of DLLs and dates.
OLE 2. The Next Step
 OLE 1.0 did not succeed because of various limitations.
 The need was for a document to load and save an object that it did not know about.
 The application should provide an interface to edit objects that it contains.
 To support drag-and-drop of objects that it does not know about.
 To execute commands on objects belonging to unknown applications.
 Demands of this type meant budding applications/objects that could be used by any other application. A
standard had to be developed or evolved which all object builders would follow.
 This example can be seen in the case of hardware. When one talks of RS232C everybody knows what it
means. Anybody in the business of serial communications would build products that follow this standard in
terms of connections, size, number of pins, etc.
 Visualize the hardware scenario and use the same analogy for software.
 OLE 2.0 attempted to meet all the conditions by bringing together different technologies under one
umbrella.
 We first need to understand in simple terms the meaning of an object in this context. An object is (at this
stage of discussion) the data that is embedded in your document. For example, if you have included a part
of a spreadsheet in your Word document, the spreadsheet is an embedded object. The task now is to figure
out how this 'object' can be controlled, invoked, deleted, etc.

111

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 Microsoft came up with some specifications on Objects and how they should be handled. The
specifications are as under, and are COM specifications. COM stands for Component Ob¬ject Model, the
new buzzword in computers.
1. A common method for applications to exchange objects.
2. A method to identify an object and relate an object with applications that can manipu- late it.
3. A standard set of error codes and an error-reporting and responding system.
4. A system to invoke an object. Check if it is in use, and delete it if it is not in use. This ensures
that memory resources are not blocked.
5. A set of rules for applications to access and manipulate objects.
 Let us see how these rules can be applied. Let us take an example of a Word document containing a part
of an Excel spreadsheet.
 An application that accepts or requests an object is called as the client or container.
 The application that provides an object is called the Server.
Rulel :
 Word must know how to accept the spreadsheet from Excel.
Rule2 :
 If the user double-clicks on the spreadsheet, Word (or the system) must be able to identify the
object and invoke Excel.
Rule3 :
 In case of an error like Excel being corrupted or “This application has performed.../ Error, both
the applications must be notified. A copy of the FIR is to be sent to the MLA!
Rule 4:
 Once the modifications have been completed on the object, the instance of Excel must be closed.
This will ensure that resources are not blocked.
Rule 5 :
 This ensures that the spreadsheet is presented as a spreadsheet, and that the rules for presenting
spreadsheet data are followed.
 Identifying the object: Every time an object is created, identification for this is created. This is called
GUID, which means Globally Unique Identifier. The GUID is a 16Byte value that is totally unique.
The object is identified by the GUID rather than by any name that the user may give.
 This means that a Word document for example can have multiple objects from the same or different
applications. Once the object has been identified, the container application allows the object to draw
itself. Identifying the application(s) associated with the object does this.
 There is something called 'in-place-editing' where the objects application will take control of the object
and allow the user access to all its tools.
 Saving the object: This is called persistence. Very soon our current dictionaries will go out of vogue. If
a document contains multiple objects, how is it going to save itself and all the objects? According to
COM, every object must be able to save and load itself. A set of specifications has been defined for
saving and loading objects, but where and how will different objects store their data?
 OLE Structured Storage is the answer. It is like a file system within a file. The file becomes the
directory, known as storage, and each of the objects becomes the file (known as stream) in the
directory. Therefore in our example, the Word file will create a Storage and pass it to the objects.
 The objects will save themselves as streams in the Storage. Since the GUID of the objects are also
saved, it is easy for the objects to load themselves as and when required.
OLE Automation
 This is a mechanism by which a container application can execute commands in the server application.
This also allows the container application to export or transfer data from the objects to another
application. When Visual Basic was first released, it made developing Windows applications easy.
 Longer did programmers have to fight with C and C++ and similar animals. Developers started creating
controls that could be used by other Visual Basic programmers. Microsoft encouraged this trend. A
programmer could buy a number of controls in the market, wire them together and have an application
ready. We have done the same thing in the previous exercises.
 Let us take a look at the controls. Each control is independent. It has its data, properties, etc. It can
display as well as draw itself on the form. It can be changed at design time or runtime if necessary. The
functions that make it work are kept in a DLL.

112

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 The VBX were like the COM objects by design or chance, but their limitation was that they could work
only with Visual Basic. Therefore OLE was taken out of the dungeon and worked upon, it had all the
features for component programming, but could not raise events in the container application.
 OLE was thus extended. It came to be known as OCX or OLE Control, which could raise events in the
container applications. We have thus seen the evolution of programming combined with market events.
Let us take a look at another market event that brought about ActiveX.
 Microsoft was working steadily on the path to 'docu-centric computing', when suddenly there was a
big bang in the form of the Internet and the World Wide Web. Everybody was talking about it.
 Microsoft was not really prepared for it. Microsoft took a closer look at HTML and found that the
concept of'docu-centric computing was very well implemented here. As a leading company, it needed
to tell one and all that it had a technology for the Internet. They called this technology ActiveX.
ActiveX is OLE with some extensions for the Internet.
 Now that the cat is out of the bag, let us take a look at some of the properties of ActiveX controls.
 Any control or object has
 Properties : like BackColour, Font, Resize, Paint, etc.
 Events : Click, MouseMove, KeyPress, LostFocus, etc.
 Methods: The code associated with the control.
 So is the case with an ActiveX object or control.
So How is an ActiveX Control Different?
 ActiveX controls are created by using existing controls, or from scratch.
 An ActiveX control can be used by other development tools as well.
 Controls like MSFlexGrid, Sheridan Controls are all ActiveX controls.
So what is the big idea?
 With Visual Basic 5.0 onwards you can create your own ActiveX controls. Any control that you see or
use can be enhanced to suit your requirements.
 That control can be used in your organization, or you can sell it to your neighbour and make some pocket
money. An existing control can be restricted and used in your application. The dream of reusable code
has now become a reality, thanks to ActiveX.
 Now let us create an ActiveX control.
 We know that ActiveX is not a strange, dangerous, complex and shaggy animal. It is a simple thing
after all. Let us create a simple ActiveX first.Click Start your Visual Basic.Start a new project.
Select ActiveX Control from the various options.
 You will see a new Form. Notice that it looks like another form that you have been playing around
with. The title bar will say "UserControll". This means that you are creating your own control
(ActiveX Control). Touch your head. You have not grown a horn yet!
 Now change the name of the UserControll to a name of your choice. You do so by clicking on the
form and pressing F4. Sounds familiar?
 Save this user control in the respective files. An ActiveX control is saved in a file with .ctl extension.
There will also be a .vbp file. You have just created an ActiveX control. Let us see it in action.
 Open the project again. Click on File and select Add Project.
 Select Standard Exe this time. Observe your Project Explorer. Notice that there are two projects
listed. You will be constantly shifting from one to the other, as you work along, lb the Standard.Exe
project form Forml, add the new User Control that you just created.
 You will see another blank window that does not do anything at all. This ActiveX is not active! That
is because you have not added any control on it yet, nor have you set any methods or pictures, etc.
Registering an ActiveX Control
1. First delete the second project where you had tried out the user control.
2. From the file menu choose the option ‘Make….OCX’
This will register the new control in your window system directory. the control is now available to
you and to those who use your system.
3. To add this control in the Toolbox, go to the windows\System directory.
4. Run the command “regsvr32 [controlName].ocx” to register this control.
ActiveX AND WEB PAGES: OBJECTIVES
 ActiveX and Internet.
113

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

Microsoft ActiveX Control Pad.


Creating a Web Page.
What is HTML? Some of the terms used.
Placing an ActiveX Control on the Page.
ActiveX AND INTERNET
Explain in detail about ActiveX and webpages with an example. (10 Marks)
 ActiveX Documents go well with the Microsoft's strategy for the Internet.
 When we talk of Internet we must necessarily talk of HTML, as it is the language of the World Wide
Web or WWW.
 The Internet is a collection of computers that are wired together and talk in TCP/IP. The World Wide
Web is a collection of documents that are linked together. The documents are viewed by the users in the
form of Pages. The Pages will have topics that are linked to other topics and so forth. These page8 are
read by what is called as Internet Browsers. Of course you know that! The browsers understand a
language called HTML, or Hypertext Mark-up Language.
 All page that have to be placed on the Web have to be created using this language. ActiveX Controls can
be added to Web Pages to improve the functionality of the Page. An ActiveX control can be loaded on
the page to play a movie clip.avi file or to present a form.
 Microsoft has provided a new tool to simplify the addition of ActiveX controls to a Page. This tool is
called Microsoft ActiveX Control Pad.
 As of now, it is available FREE! We will first create a simple Page with an ActiveX control on it.
 The ActiveX Control that we have developed during our last session has to be sold! Let us tell the world
about it. Let us also talk about our Alma Mater! Our Page must have a Title! It must have a line that will
introduce us. A line to provide further information. A picture to give an idea about what we can do!
 Instead of the picture, let us show them the Calendar Control that we have developed. We should talk
about the other services offered by EMSQUARE.
 Let the user click a spot and we can pop up a panel to list our courses and services. We can also pop up
another panel to list the other control that we have developed (or borrowed. Visual Basic is a good
place.) So we know what to do.
 The tool to use is the Microsoft ActiveX Control Pad! God Bless the King! Let us begin. Check if you
have installed the ActiveX Control Pad. Click start the Control Pad, and you will see a screen that looks
like the figure below.

 Let us take a quick look at what is there in an HTML file.


 An HTML page begins with a tag <HTML>. This tag tells the browser that the file is an HTML file, and
hence must be treated with respect.
What is a tag?
 An HTML page can contain text with different styles. Each style for the sake of (our) convenience can
be called a para. Each para is preceded by a tag and ends with a tag. A tag is a bit of text that tells the
browser how the following text has to be read and displayed.
 The ending tag for a para will tell the browser that the para has come to an end and the next definition if
any will begin with the next tag. The HEAD section includes the title of the page and the name of the
creator of this page, etc. The BODY section is where most of the action is. You can add text here or
pictures, or other controls.
Some definitions are here for you:

114

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

1. HTTP: Hypertext Transfer Protocol. This protocol is used to transfer pages from the server to the
client.
2. Server: The computer that has the pages that you requested.
3. Client: Your computer that has made the request.
4. URL: Uniform Resource Locator. This contains the information needed to locate the page that you
want. An URL has
 The Protocol
 The Server name
 The Pathname of the file in the server's directory
 PageName, the name of the file that has the page
 Pagenumber#, the Pagenumber which hold the text that you want.
 We will cover tags as we continue with development.
 Now let us get back to the ActiveX Control Pad. Right Click the Mouse between the tags <BODY> and
</BODY>. From the pop-up menu choose "Insert ActiveX Controls".
 A list of ActiveX control will pop. You will be surprised that there are already so many ActiveX
Controls available on your system.
 Select the Calendar Control that we developed.

 Now save changes on the file. Open the file using Windows Explorer.
 You will see your first HTML page. Congratulations!

 Now let us do some menial work.


 Remember that HTML uses tags to tell the browser about the various properties of the text.
 Have you had the pleasure of working on WordStar, the early word processor? You will remember the
way we used to print a line in bold by pressing " ^PB" (CTRL+P+B). At the end of the line we used to
once again enter "^PB" (CTRL+P+B).
 You will have to do something very similar here to achieve the results that we want.

 Take a look at the following code.


115

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 The ActiveX based web page would look like the below screen shot.

SAMPLE APPLICATION IN VB LIKE INVENTORY CONTROL


Write in detail about inventory control application using VB. (10 Marks)
 When you go the supermarket or to a drug store and make your purchase, the person at the counter will
give you a piece of paper along with your purchase.
 More often than not you do not bother to read it and forgetting your civic responsibility you throw the
paper along the way.
 The paper you threw away is the bill of sale. It tells you the name of the shop and the quantity and rate at
which you have purchased the goods.
 An invoice is a bill sent to the purchaser demanding payment for goods or services delivered.
 If the Invoice is presented to the customer he should naturally pay up. Ok! So you know what is an
invoice? The retailer 'stocks and sells' the goods. Just as a Library 'stocks and issues' books and periodicals.
 The Retailer gets the 'stock' from the manufacturer or the Distributor. (We will refer to them as Suppliers).
This means that the Retailer has to pay for the goods received from the Suppliers either immediately or
after a certain period of time. Usually the Suppliers supply-goods on 'Credit' to the Retailers.
 The Retailer will sell from his stock to the consumer. (We will refer to the consumer as Customer). The
customer can also be another retailer.
 Depending upon the nature of the business and the prevailing conditions, the Customers pay for the goods
immediately or later.
 A retailer therefore deals with two types of people. The Suppliers and the Customers.
The Supplier
116

Downloaded by Logesh krishnan ([email protected])


lOMoARcPSD|42888207

 From the Supplier the retailer will receive goods and pay for them. Retailers will generally have a couple
of 'regular' suppliers.
 The regular suppliers will also extend credit and certain Understanding exists between them. The retailer
must keep track of the amount that he has to pay to his suppliers.
 This is referred to as 'Payables'. The retailer will also buy from a number of other suppliers who may or
may not extend credit. These suppliers normally supply good* during seasonal or unexpected demand.
The Customer
 The Customer is the consumer. He buys from the retailer (normally) in small quantities and pays 'cash on
the barrel'. A number of customers also pay for the goods later.
 This is where the retailer has to keep track of payments due from his customers. In commercial jargon this
is referred to as 'Outstanding' or Receivables.
 Another important factor now in the distribution set up is the stock.
The Stock
 The retailer maintains a stock of goods that he believes will be purchased by the local junta. If he makes a
wrong guess he is left with a lot of stock that has to be disposed of under the banner 'Closing Shop!
Distress Sale!' The stock in the shop or the warehouse of the retailer is called 'Stock on hand'.
 Based on the sale of goods, the retailer will replenish the stock. For even* item the retailer will maintain a
'Reorder Level'.
 The Re-order Level is a function of various factors like Demand for the goods, the Lead time to supply,
etc. If for example Potatoes are selling like hot cakes' and the lead time to supply (the time between
ordering for and receiving the items') is high then the re-order level is also high.
 This is so because, by the time the fresh stock arrives, the retailer should not end up with an empty bin 1 f
the Lead-time to supply is very low then the re-Order level can also be low
 Now what should the size of order be? One kilo? One ton? One truckload? This quantity is called
Minimum Order Quantity or Economic Order Quantity. The MOQ is arrived at taking into account
quantity discounts offered by the suppliers, the demand for the goods in his area and other related factors.
 You cannot order one kilo of nee from a distributor who deals in truckloads. So you know what is meant
by Minimum Order Quantity.
 The retailer must send a Purchase Order to the supplier for goods. The Purchase Order (PO) may be based
on a quotation sent by the supplier or it may be a PO without the rates.
 The Supplier will send the goods based on the current prices. Once the goods arrive, they have to be
accepted' in the store. A document called the Goods Received Note' is generated.
 This is considered an important document based on which the supplier will be paid this is so because the
supplier may not have sent all the goods ordered or there may be a 'Short Shipment'.
 From the above description we see that the retailer carries out the following activity’s
1. Raising a Purchase Order
2. Accepting the goods into the store
3. Making a payment to the Supplier.
4. Selling goods to the Customer.
 Sending a quotation (in some cases),
 Accepting the Order from the Customer,
 Raising an Invoice.
5. Receiving payment from the customer.
6. Maintaining stocks.
 Different set of tables are created for supplies, stock and customer and relationships are established between
them depending upon the requirement of the application.

||***********************End of Unit –V***********************||

Text Book Referred:


1. Programming with Visual Basic 6.0 by Mohammed Azam.

117

Downloaded by Logesh krishnan ([email protected])

You might also like