0% found this document useful (0 votes)
2 views333 pages

1728973795-Visual Basic Lesson Notes

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)
2 views333 pages

1728973795-Visual Basic Lesson Notes

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

Visual Basic

UNIT I
Getting Started with VB6, Programming
Environment, Working with Forms, Developing
an application, Variables, Data types and
Modules, procedures and control structures,
arrays. Working with Controls: Creating and
using controls, working with control arrays.

[Link] to Visual Basic

What is Visual Basic?

Visual Basic is a third-generation event-driven


programming language first released by Microsoft in
1991. It evolved from the earlier DOS version called
BASIC. BASIC means Beginners' All-purpose
Symbolic Instruction Code. Since then Microsoft has
released many versions of Visual Basic, from Visual
Basic 1.0 to the final version Visual Basic 6.0. Visual
Basic is a user-friendly programming language
designed for beginners, and it enables anyone to
develop GUI window applications easily.

In 2002, Microsoft released Visual


[Link]([Link]) to replace Visual Basic 6.

1
Thereafter, Microsoft declared VB6 a legacy
programming language in 2008. Fortunately,
Microsoft still provides some form of support for
VB6. [Link] is a fully object-oriented programming
language implemented in the .NET Framework. It was
created to cater for the development of the web as well
as mobile applications. However, many developers
still favor Visual Basic 6.0 over its successor Visual
[Link].

1.1 Programming Environment

Visual Basic is initiated by using the Programs option


> Microsoft Visual Basic 6.0 > Visual Basic 6.0.
Clicking the Visual Basic icon, we can view a
copyright screen enlisting the details of the license
holder of the copy of Visual Basic 6.0. Then it opens
in to a new screen as shown in figure 1 below, with the
interface elements Such as MenuBar, ToolBar, The
New Project dialog box. These elements permit the
user to buid different types of Visual Basic
applications.

The Integrated Development Environment

One of the most significant changes in Visual Basic


6.0 is the Integrated Development Environment (IDE).
IDE is a term commonly used in the programming

2
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

In previous versions of Visual Basic, the IDE was


designed as a Single Document Interface (SDI). In a
Single Document Interface, each window is a free-
floating window that is contained within a main
window and can move anywhere on the screen as long
as Visual Basic is the current application. But, in
Visual Basic 6.0, the IDE is in a Multiple Document

3
Interface (MDI) format. In this format, the windows
associated with the project will stay within a single
container known as the parent. Code and form-based
windows will stay within the main container form.

Getting Started with Visual Basic 6.0


Figure 1 The Visul Basic startup dialog box

4
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.

5
Toolbox

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.

Figure 2 Toolbox window with its controls


available commonly.

6
Control Description

Provides a way to move and


Pointer
resize the controls form

Displays icons/bitmaps and


metafiles. It displays text or
PictureBox
acts as a visual container for
other controls.

Used to display message and


TextBox
enter text.

Serves as a visual and


Frame functional container for
controls

Used to carry out the


CommandButton specified action when the
user chooses it.

Displays a True/False or
CheckBox
Yes/No option.

OptionButton control which


is a part of an option group
OptionButton allows the user to select only
one option even it displays
mulitiple choices.

7
Displays a list of items from
ListBox
which a user can select one.

Contains a TextBox and a


ListBox. This allows the
user to select an ietm from
ComboBox
the dropdown ListBox, or to
type in a selection in the
TextBox.

These controls allow the


HScrollBar and
user to select a value within
VScrollBar
the specified range of values

Executes the timer events at


Timer
specified intervals of time

Displays the valid disk


DriveListBox drives and allows the user to
select one of them.

Allows the user to select the


DirListBox directories and paths, which
are displayed.

Displays a set of files from


FileListBox which a user can select the
desired one.

Shape Used to add shape

8
(rectangle, square or circle)
to a Form

Used to draw straight line to


Line
the Form

used to display images such


as icons, bitmaps and
Image
metafiles. But less capability
than the PictureBox

Enables the use to connect


Data to an existing database and
display information from it.

Used to link or embed an


object, display and
OLE
manipulate data from other
windows based applications.

Displays a text that the user


Label 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

9
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 is docked under the Project


Explorer window. The Properties Window exposes the
various characteristics of selected objects. Each and

10
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.

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
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.

11
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
1.3 Working with Forms

The Appearance of Forms


The main characteristic of a Form is the title bar on
which the Form's caption is displayed. On the left end
of the title bar is the Control Menu icon. Clicking this
icon opens the Control Menu. Maximize, Minimize
and Close buttons can be found on the right side of the
Form. Clicking on these buttons performs the
associated function.

The following figure illustrates the appearance of a

12
Form

The control menu contains the following commands :

• Restore : Restores a maximized Form to the


size it was before it was maximized; available
only if the Form has been maximized.
• Move : Lets the user moves the Form around
with the mouse
• Size : Lets the user resizes the control with
the mouse
• Minimize: Minimizes the Form
• Maximize : Maximizes the Form
• Close : Closes the Form

13
Setting the Start-Up Form

A typical application has more than a single Form.


When an application runs the main Form is loaded. By
setting the Project properties you can control which
Form is to be displayed in the Start-Up of the
application. Following figure illustrates the Project
property window.

By default, Visual Basic suggests the name of the first


Form created when the project started.

Loading and Unloading Forms

In order to load and unload the forms, Load and


Unload statements are used. The Load statement has

14
the following syntax :

Load FormName

And the Unload statement has the following syntax :

Unload FormName

The FormName variable is the name of the Form to be


loaded or unloaded. Unlike the Show method which
cares of both loading and displaying the Form, the
load statement doesn't show the Form. You have to
call the Form's Show method to display it on the
desktop.

Showing and Hiding Forms

Show method is used to Show a Form. If the Form is


loaded but invisible, the Show method is used to bring
the Form on Top every other window. If the Form is
not loaded, the Show method loads it and then displays
it.

Syntax of the Show method of the Form

[Link] mode

The FormName variable is the Form's name, and the

15
optional argument mode determines whether the Form
will be Modal or not. It can have one of the following
syntax :

* 0-Modeless (default)

* 1-Modal

Modeless Forms are the normal Forms. Modeless


Forms interact with the user and the user allowed to
switch to any other Form of the application. If you do
not specify the optional mode argument, by default the
mode is set to modeless.

The Modal Forms takes the total control of the


application where user cannot switch to any other
Forms in the application unless the Form is closed. A
modal Form, thus, must have a Close button or some
means to close the Form in order to return to the Form
where the Modal Form was loaded.

Hiding Forms

The Hide method is used to hide a Form. The


following is the syntax of the Hide Method.

[Link]

16
To hide a Form from within its own code, the
following code can be used.

[Link]

You must understand that the Forms that are hidden


are not unloaded ; they remains in the memory and can
be displayed instantly with the Show Method. When a
Form is hidden, you can still access its properties and
code. For instance, you can change the settings of its
Control Properties or call any Public functions in the
Form.

The following is an example illustrates the Show


method and Mode statement

* Open a new Project and save the Project

Design the application as shown below


Object Property Setting
Caption Form1
Form
Name frm1
Caption Form2
Form
Name frm2

17
Caption Form3
Form
Name frm3
Click on a button to display a
Caption
Form
Label
Name
Label1

The following code is typed in the Click event of the


command buttons

18
Run the application. Clicking on the buttons will
display the Forms respectively. But you can see that in
the cmd2_Click( ) event additionally VbModal
argument has been added. You can see the difference
after you display the forms by clicking on the
command buttons. You can notice that you cannot
switch to any other Forms in the application unless
you close the Form3.

Finding out the difference between Unload and


Hide method

To know what the difference is between Unload and


Hide methods we will do an example. Open a new
project and save the project. Draw two buttons on the
form and name those as shown above.

19
In the click event of the Hide button Following code is
entered.

[Link]

In the click event of the Unload button following code


is entered.

Unload Me

Save the project and run the application. Once you


click on Hide button you can note that the Form is
invisible but the application is still running. But when
you click on Unload button you can see that the
application is terminated.

1.4 Developing an Application

Steps in Building a Visual Basic Application

Step 1: Design the interface by adding controls to the


form and set their properties

Step 2:Write code for the event procedures

20
Example 2.2 Changing Background and Foreground
Color at Random

In this example, we want to show you how to write


code to change the background and the foreground
color randomly. We will place two command buttons
and a label on the form. One of the command buttons
will be used to change the background color while the
other one will be used to change the foreground color.
The Label is for displaying the foreground color.
There are two events here, change background color
and change foreground color. Therefore, we need to
write code for the two event procedures.

To make the program more interesting, we will use the


Rnd() function, the Int() function and the RGB codes
to change the color randomly. The Rnd() function
creates a random number between 0 and 1 and the
RGB code uses a combination of three integers to
form a certain color. The Int() is a function that
converts a number into an integer by truncating its
decimal part and the resulting integer is the largest
integer that is smaller than the number. For example,
Int(0.2)=0, Int(2.4)=2, Int(4.8)=4. Therefore,
Int(Rnd()*256) returns the smallest integer 0 and the
biggest integer 255. The format of RGB code is
RGB(a,b,c), where a, b, c range from 0 to 255. For
example, RGB(255,0,0) is red, RGB(255,255,255) is

21
white and (0,0,0) is black. Do not worry about the
jargons, you will learn them in later lesson.

Now, rename the controls as follows:

• Form1-MyForm
• Label1-LblMessage
• Command1-cmd_bgColor
• Command2-cmd_fgColor

Next, change the caption of the Label to "Please


Change My Color". In addition, change the caption of
Command1 button to "Change Background Color" and
change the caption of Command2 button to "Change
Foreground Color"

Now, enter the following code

Private Sub cmd_bgColor_Click()


Dim r, g, b As Integer
r = Int(Rnd() * 256)
g = Int(Rnd() * 256)
b = Int(Rnd() * 256)
[Link] = RGB(r, g, b)
End Sub

Private Sub Cmd_fgColor_Click()


Dim r, g, b As Integer

22
r = Int(Rnd() * 256)
g = Int(Rnd() * 256)
b = Int(Rnd() * 256)
Lbl_Msg.ForeColor = RGB(r, g, b)
End Sub

When you run the program, each time you press on the
'Change Background Color' button, you will see
different background color. Similarly, each time you
press on the 'Change Foreground Color', you will see
the message on the Label changes color. The output is
shown in Figure 4.

Figure 4.

23
[Link] Fundamentals
2.1Variables in Visual Basic
Variables are the memory locations which are used to
store values temporarily. A defined naming strategy
has to be followed while naming a variable. A variable
name must begin with an alphabet letter and should
not exceed 255 characters. It must be unique within
the same scope. It should not contain any special
character like %, &, !, #, @ or $.
There are many ways of declaring variables in Visual
Basic. Depending on where the variables are declared
and how they are declared, we can determine how they
can be used by our application. The different ways of
declaring variables in Visual Basic are listed below
and elucidated in this section.

• Explicit Declaration
• Using Option Explicit statement
• Scope of Variables

Explicit Declaration

Declaring a variable tells Visual Basic to reserve space


in memory. It is not must that a variable should be
declared before using it. Automatically whenever
Visual Basic encounters a new variable, it assigns the
default variable type and value. This is called implicit
declaration. Though this type of declaration is easier
for the user, to have more control over the variables, it

24
is advisable to declare them explicitly. The variables
are declared with a Dim statement to name the
variable and its type. The As type clause in the Dim
statement allows to define the data type or object type
of the variable. This is called explicit declaration.

Syntax

Dim variable [As Type]

For example,

Dim strName As String


Dim intCounter As Integer

Using Option Explicit statement

It may be convenient to declare variables implicitly,


but it can lead to errors that may not be recognized at
run time. Say, for example a variable by name intcount
is used implicitly and is assigned to a value. In the
next step, this field is incremented by 1 by the
following statement

Intcount = Intcount + 1

This calculation will result in intcount yielding a value


of 1 as intcount would have been initialized to zero.

25
This is because the intcount variable has been mityped
as incont in the right hand side of the second variable.
But Visual Basic does not see this as a mistake and
considers it to be new variable and therefore gives a
wrong result.

In Visual Basic, to prevent errors of this nature, we


can declare a variable by adding the following
statement to the general declaration section of the
Form.

Option Explicit

This forces the user to declare all the variables. The


Option Explicit statement checks in the module for
usage of any undeclared variables and reports an error
to the user. The user can thus rectify the error on
seeing this error message.

The Option Explicit statement can be explicitly placed


in the general declaration section of each module using
the following steps.

• Click Options item in the Tools menu


• Click the Editor tab in the Options dialog box
• Check Require Variable Declaration option
and then click the OK button

26
Scope of variables

A variable is scoped to a procedure-level (local) or


module-level variable depending on how it is declared.
The scope of a variable, procedure or object
determines which part of the code in our application
are aware of the variable's existence. A variable is
declared in general declaration section of e Form, and
hence is available to all the procedures. Local
variables are recognized only in the procedure in
which they are declared. They can be declared with
Dim and Static keywords. If we want a variable to be
available to all of the procedures within the same
module, or to all the procedures in an application, a
variable is declared with broader scope.

Local Variables

A local variable is one that is declared inside a


procedure. This variable is only available to the code
inside the procedure and can be declared using the
Dim statements as given below.

Dim sum As Integer

The local variables exist as long as the procedure in


which they are declared, is executing. Once a
procedure is executed, the values of its local variables
are lost and the memory used by these variables is

27
freed and can be reclaimed. Variables that are declared
with keyword Dim exist only as long as the procedure
is being executed.

Static Variables

Static variables are not reinitialized each time Visual


Invokes a procedure and therefore retains or preserves
value even when a procedure ends. In case we need to
keep track of the number of times a command button
in an application is clicked, a static counter variable
has to be declared. These static variables are also ideal
for making controls alternately visible or invisible. A
static variable is declared as given below.

Static intPermanent As Integer

Variables have a lifetime in addition to scope. The


values in a module-level and public variables are
preserved for the lifetime of an application whereas
local variables declared with Dim exist only while the
procedure in which they are declared is still being
executed. The value of a local variable can be
preserved using the Static keyword. The follwoing
procedure calculates the running total by adding new
values to the previous values stored in the static
variable value.

28
Function RunningTotal ( )
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function

If the variable Accumulate was declared with Dim


instead of static, the previously accumulated values
would not be preserved accross calls to the procedure,
and the procedure would return the same value with
which it was called. To make all variables in a
procedure static, the Static keyword is placed at the
beginning of the procedure heading as given in the
below statement.

Static Function RunningTotal ( )

Example: The following is an example of an event


procedure for a CommandButton that counts and
displays the number of clicks made.

Private Sub Command1_Click ( )


Static Counter As Integer
Counter = Counter + 1
Print Counter
End Sub

29
The first time we click the CommandButton, the
Counter starts with its default value of zero. Visual
Basic then adds 1 to it and prints the result.

Module Levele Variables

A module level variable is available to all the


procedures in the module. They are declared using the
Public or the Private keyword. If you declare a
variable using a Private or a Dim statement in the
declaration section of a module—a standard BAS
module, a form module, a class module, and so on—
you're creating a private module-level variable. Such
variables are visible only from within the module they
belong to and can't be accessed from the outside. In
general, these variables are useful for sharing data
among procedures in the same module:

' In the declarative section of any module


Private LoginTime As Date ' A private module-level
variable
Dim LoginPassword As String ' Another private
module-level variable

You can also use the Public attribute for module-level


variables, for all module types except BAS modules.
(Public variables in BAS modules are global
variables.) In this case, you're creating a strange beast:
a Public module-level variable that can be accessed by

30
all procedures in the module to share data and that also
can be accessed from outside the module. In this case,
however, it's more appropriate to describe such a
variable as a property:

' In the declarative section of Form1 module


Public CustomerName As String ' A Public property

You can access a module property as a regular


variable from inside the module and as a custom
property from the outside:

' From outside Form1 module...


[Link] = "John Smith"

The lifetime of a module-level variable coincides with


the lifetime of the module itself. Private variables in
standard BAS modules live for the entire life of the
application, even if they can be accessed only while
Visual Basic is executing code in that module.
Variables in form and class modules exist only when
that module is loaded in memory. In other words,
while a form is active (but not necessarily visible to
the user) all its variables take some memory, and this
memory is released only when the form is completely
unloaded from memory. The next time the form is re-
created, Visual Basic reallocates memory for all
variables and resets them to their default values (0 for

31
numeric values, "" for strings, Nothing for object
variables).

Public vs Local Variables

A variable can have the same name and different


scope. For example, we can have a public variable
named R and within a procedure we can declare a
local variable R. References to the name R within the
procedure would access the local variable and
references to R outside the procedure would access the
public variable.

2.2 Visual Basic 6 (VB6) Data Types, Modules


and Operators
Visual Basic uses building blocks such as Variables,
Data Types, Procedures, Functions and Control
Structures in its programming environment. This
section concentrates on the programming
fundamentals of Visual Basic with the blocks
specified.

Modules

Code in Visual Basic is stored in the form of modules.


The three kind of modules are Form Modules,
Standard Modules and Class Modules. A simple
application may contain a single Form, and the code

32
resides in that Form module itself. As the application
grows, additional Forms are added and there may be a
common code to be executed in several Forms. To
avoid the duplication of code, a separate module
containing a procedure is created that implements the
common code. This is a standard Module.

Class module (.CLS filename extension) are the


foundation of the object oriented programming in
Visual Basic. New objects can be created by writing
code in class modules. Each module can contain:

Declarations : May include constant, type, variable


and DLL procedure declarations.

Procedures : A sub function, or property procedure


that contain pieces of code that can be executed as a
unit.

These are the rules to follow when naming elements in


VB - variables, constants, controls, procedures, and so
on:

• A name must begin with a letter.


• May be as much as 255 characters long (but
don't forget that somebody has to type the
stuff!).

33
• Must not contain a space or an embedded
period or type-declaration characters used to
specify a data type; these are ! # % $ & @
• Must not be a reserved word (that is part of
the code, like Option, for example)
• The dash, although legal, should be avoided
because it may be confused with the minus
sign. Instead of First-name use First_name or
FirstName.

Data types in Visual Basic 6

By default Visual Basic variables are of variant data


types. The variant data type can store numeric,
date/time or string data. When a variable is declared, a
data type is supplied for it that determines the kind of
data they can store. The fundamental data types in
Visual Basic including variant are integer, long, single,
double, string, currency, byte and boolean. Visual
Basic supports a vast array of data types. Each data
type has limits to the kind of information and the
minimum and maximum values it can hold. In
addition, some types can interchange with some other
types. A list of Visual Basic's simple data types are
given below.

34
1. Numeric
Store integer values in the range of 0 -
Byte
255
Store integer values in the range of (-
Integer
32,768) - (+ 32,767)
Store integer values in the range of (-
Long
2,147,483,468) - (+ 2,147,483,468)
Store floating point value in the range of
Single
(-3.4x10-38) - (+ 3.4x1038)
Store large floating value which
Double
exceeding the single data type value
store monetary values. It supports 4
Currency digits to the right of decimal point and
15 digits to the left

2. String

Use to store alphanumeric values. A variable length


string can store approximately 4 billion characters

3. Date

Use to store date and time values. A variable declared


as date type can store both date and time values and it
can store date values 01/01/0100 up to 12/31/9999

35
4. Boolean

Boolean data types hold either a true or false value.


These are not stored as numeric values and cannot be
used as such. Values are internally stored as -1 (True)
and 0 (False) and any non-zero value is considered as
true.

5. Variant

Stores any type of data and is the default Visual Basic


data type. In Visual Basic if we declare a variable
without any data type by default the data type is
assigned as default.

Operators in Visual Basic

Arithmetical Operators Table

Operators Description Example Result

+ Add 5+5 10
- Substract 10-5 5
/ Divide 25/5 5
\ Integer 20\3 6

36
Division
* Multiply 5*4 20
Exponent
^ 3^3 27
(power of)
Remainder of
Mod 20 Mod 6 2
division
String "George"&" "George
&
concatenation "&"Bush" Bush"

Relational Operators

Operators Description Example Result


Greater
> 10>8 True
than
< Less than 10<8 False
Greater
>= than or 20>=10 True
equal to
Less than or
<= 10<=20 True
equal to
Not Equal
<> 5<>4 True
to
= Equal to 5=7 False

37
Logical Operators
Operators Description
Operation will be true if either of the
OR
operands is true
Operation will be true only if both the
AND
operands are true

2.3 Procedures in Visual Basic 6

Visual Basic offers different types of procedures to


execute small sections of coding in applications. The
various procedures are elucidated in details in this
section. Visual Basic programs can be broken into
smaller logical components called Procedures.
Procedures are useful for condensing repeated
operations such as the frequently used calculations,
text and control manipulation etc. The benefits of
using procedures in programming are:

It is easier to debug a program a program with


procedures, which breaks a program into discrete
logical limits.

38
Procedures used in one program can act as building
blocks for other programs with slight modifications.

A Procedure can be Sub, Function or Property


Procedure.

Sub Procedures

A sub procedure can be placed in standard, class and


form modules. Each time the procedure is called, the
statements between Sub and End Sub are executed.
The syntax for a sub procedure is as follows:

[Private | Public] [Static] Sub Procedurename [(aglst)]


[ statements]
End Sub

aglst is a list of argument names separated by commas.


Each argument acts like a variable in the procedure.
There are two types of Sub Procedures namely general
procedures and event procedures.

Event Procedures

An event procedure is a procedure block that contains


the control's actual name, an underscore(_), and the
event name. The following syntax represents the event
procedure for a Form_Load event.

39
Private Sub Form_Load()
....statement block..
End Sub

Event Procedures acquire the declarations as Private


by default.

General Procedures

A general procedure is declared when several event


procedures perform the same actions. It is a good
programming practice to write common statements in
a separate procedure (general procedure) and then call
them in the event procedure.

In order to add General procedure:

• The Code window is opened for the module


to which the procedure is to be added.
• The Add Procedure option is chosen from the
Tools menu, which opens an Add Procedure
dialog box as shown in the figure given
below.
• The name of the procedure is typed in the
Name textbox
• Under Type, Sub is selected to create a Sub
procedure, Function to create a Function
procedure or Property to create a Property
procedure.

40
• Under Scope, Public is selected to create a
procedure that can be invoked outside the
module, or Private to create a procedure that
can be invoked only from within the module.

We can also create a new procedure in the current


module by typing Sub ProcedureName, Function
ProcedureName, or Property ProcedureName in the
Code window. A Function procedure returns a value
and a Sub Procedure does not return a value.

41
Function Procedures

Functions are like sub procedures, except they return a


value to the calling procedure. They are especially
useful for taking one or more pieces of data, called
arguments and performing some tasks with them.
Then the functions returns a value that indicates the
results of the tasks complete within the function.

The following function procedure calculates the third


side or hypotenuse of a right triangle, where A and B
are the other two sides. It takes two arguments A and
B (of data type Double) and finally returns the results.

Function Hypotenuse (A As Double, B As Double) As


Double
Hypotenuse = sqr (A^2 + B^2)
End Function

The above function procedure is written in the general


declarations section of the Code window. A function
can also be written by selecting the Add Procedure
dialog box from the Tools menu and by choosing the
required scope and type.

Property Procedures

A property procedure is used to create and manipulate


custom properties. It is used to create read only

42
properties for Forms, Standard modules and Class
[Link] Basic provides three kind of property
procedures-Property Let procedure that sets the value
of a property, Property Get procedure that returns the
value of a property, and Property Set procedure that
sets the references to an object.

2.4 Control Structures in Visual Basic 6.0


Control Statements are used to control the flow of
program's execution. Visual Basic supports control
structures such as if... Then, if...Then ...Else,
Select...Case, and Loop structures such as Do
While...Loop, While...Wend, For...Next etc method.

If...Then selection structure

The If...Then selection structure performs an indicated


action only when the condition is True; otherwise the
action is skipped.

Syntax of the If...Then selection


If<condition>Then
statement
End If

e.g.: If average>75 Then


[Link] = "A"
End If

43
If...Then...Else selection structure

The If...Then...Else selection structure allows the


programmer to specify that a different action is to be
performed when the condition is True than when the
condition is False.

Syntax of the If...Then...Else selection


If <condition > Then
statements
Else
statements
End If

e.g.: If average>50 Then


[Link] = "Pass"
Else
[Link] = "Fail"
End If

Nested If...Then...Else selection structure

Nested If...Then...Else selection structures test for


multiple cases by placing If...Then...Else selection
structures inside If...Then...Else structures.

Syntax of the Nested If...Then...Else selection


structure

44
You can use Nested If either of the methods as shown
above

Method 1
If < condition 1 > Then
statements
ElseIf < condition 2 > Then
statements
ElseIf < condition 3 > Then
statements
Else
Statements
End If

Method 2
If < condition 1 > Then
statements
Else
If < condition 2 > Then
statements
Else
If < condition 3 > Then
statements
Else
Statements
End If
End If
EndIf

45
e.g.: Assume you have to find the grade using nested if
and display in a text box

If average > 75 Then


[Link] = "A"
ElseIf average > 65 Then
[Link] = "B"
ElseIf average > 55 Then
[Link] = "C"
ElseIf average > 45 Then
[Link] = "S"
Else
[Link] = "F"
End If

Select...Case selection structure

Select...Case structure is an alternative to


If...Then...ElseIf for selectively executing a single
block of statements from among multiple block of
statements. Select...case is more convenient to use
than the If...Else...End If. The following program
block illustrate the working of Select...Case.

Syntax of the Select...Case selection structure

Select Case Index


Case 0
Statements

46
Case 1
Statements
End Select

e.g.: Assume you have to find the grade using


select...case and display in the text box

Dim average as Integer

average = [Link]
Select Case average
Case 100 To 75
[Link] ="A"
Case 74 To 65
[Link] ="B"
Case 64 To 55
[Link] ="C"
Case 54 To 45
[Link] ="S"
Case 44 To 0
[Link] ="F"
Case Else
MsgBox "Invalid average marks"
End Select

47
2.5 VB Array - Arrays in Visual Basic 6

An array is a consecutive group of memory locations


that all have the same name and the same type. To
refer to a particular location or element in the array,
we specify the array name and the array element
position number.

The Individual elements of an array are identified


using an index. Arrays have upper and lower bounds
and the elements have to lie within those bounds. Each
index number in an array is allocated individual
memory space and therefore users must evade
declaring arrays of larger size than required. We can
declare an array of any of the basic data types
including variant, user-defined types and object
variables. The individual elements of an array are all
of the same data type.

Declaring arrays

Arrays occupy space in memory. The programmer


specifies the array type and the number of elements
required by the array so that the compiler may reserve
the appropriate amount of memory. Arrays may be
declared as Public (in a code module), module or
local. Module arrays are declared in the general
declarations using keyword Dim or Private. Local

48
arrays are declared in a procedure using Dim or Static.
Array must be declared explicitly with keyword "As".

There are two types of arrays in Visual Basic namely:

Fixed-size array : The size of array always remains


the same-size doesn't change during the program
execution.

Dynamic array : The size of the array can be


changed at the run time- size changes during the
program execution.

Fixed-sized Arrays

When an upper bound is specified in the declaration, a


Fixed-array is created. The upper limit should always
be within the range of long data type.

Declaring a fixed-array

Dim numbers(5) As Integer

In the above illustration, numbers is the name of the


array, and the number 6 included in the parentheses is
the upper limit of the array. The above declaration
creates an array with 6 elements, with index numbers
running from 0 to 5.

49
If we want to specify the lower limit, then the
parentheses should include both the lower and upper
limit along with the To keyword. An example for this
is given below.

Dim numbers (1 To 6) As Integer

In the above statement, an array of 10 elements is


declared but with indexes running from 1 to 6.

A public array can be declared using the keyword


Public instead of Dim as shown below.

Public numbers(5) As Integer

Multidimensional Arrays

Arrays can have multiple dimensions. A common use


of multidimensional arrays is to represent tables of
values consisting of information arranged in rows and
columns. To identify a particular table element, we
must specify two indexes: The first (by convention)
identifies the element's row and the second (by
convention) identifies the element's column.

Tables or arrays that require two indexes to identify a


particular element are called two dimensional arrays.
Note that multidimensional arrays can have more than
two dimensions. Visual Basic supports at least 60

50
array dimensions, but most people will need to use
more than two or three dimensional-arrays.

The following statement declares a two-dimensional


array 50 by 50 array within a procedure.

Dim AvgMarks ( 50, 50)

It is also possible to define the lower limits for one or


both the dimensions as for fixed size arrays. An
example for this is given here.

Dim Marks ( 101 To 200, 1 To 100)

An example for three dimensional-array with defined


lower limits is given below.

Dim Details ( 101 To 200, 1 To 100, 1 To 100)

Static and dynamic arrays

Basically, you can create either static or dynamic


arrays. Static arrays must include a fixed number of
items, and this number must be known at compile time
so that the compiler can set aside the necessary
amount of memory. You create a static array using a
Dim statement with a constant argument:

51
' This is a static array.
Dim Names (100) As String

Visual Basic starts indexing the array with 0.


Therefore, the preceding array actually holds 101
items.

Most programs don't use static arrays because


programmers rarely know at compile time how many
items you need and also because static arrays can't be
resized during execution. Both these issues are solved
by dynamic arrays. You declare and create dynamic
arrays in two distinct steps. In general, you declare the
array to account for its visibility (for example, at the
beginning of a module if you want to make it visible
by all the procedures of the module) using a Dim
command with an empty pair of brackets. Then you
create the array when you actually need it, using a
ReDim statement:

' An array defined in a BAS module (with Private


scope)
Dim Customers() As String
...
Sub Main()
' Here you create the array.
ReDim Customer(1000) As String
End Sub

52
If you're creating an array that's local to a procedure,
you can do everything with a single ReDim statement:

Sub PrintReport()
' This array is visible only to the procedure.
ReDim Customers(1000) As String
' ...
End Sub

If you don't specify the lower index of an array, Visual


Basic assumes it to be 0, unless an Option Base 1
statement is placed at the beginning of the module. My
suggestion is this: Never use an Option Base statement
because it makes code reuse more difficult. (You can't
cut and paste routines without worrying about the
current Option Base.) If you want to explicitly use a
lower index different from 0, use this syntax instead:

ReDim Customers(1 To 1000) As String

Dynamic arrays can be re-created at will, each time


with a different number of items. When you re-create a
dynamic array, its contents are reset to 0 (or to an
empty string) and you lose the data it contains. If you
want to resize an array without losing its contents, use
the ReDim Preserve command:

ReDim Preserve Customers(2000) As String

53
When you're resizing an array, you can't change the
number of its dimensions nor the type of the values it
contains. Moreover, when you're using ReDim
Preserve on a multidimensional array, you can resize
only its last dimension:

ReDim Cells(1 To 100, 10) As Integer


...
ReDim Preserve Cells(1 To 100, 20) As Integer ' This
works.
ReDim Preserve Cells(1 To 200, 20) As Integer ' This
doesn't.

Finally, you can destroy an array using the Erase


statement. If the array is dynamic, Visual Basic
releases the memory allocated for its elements (and
you can't read or write them any longer); if the array is
static, its elements are set to 0 or to empty strings.

You can use the LBound and UBound functions to


retrieve the lower and upper indices. If the array has
two or more dimensions, you need to pass a second
argument to these functions to specify the dimension
you need:

Print LBound(Cells, 1) ' Displays 1, lower index of 1st


dimension
Print LBound(Cells) ' Same as above
Print UBound(Cells, 2) ' Displays 20, upper index of

54
2nd dimension
' Evaluate total number of elements.
NumEls = (UBound(Cells) _ LBound(Cells) + 1) * _
(UBound(Cells, 2) _ LBound(Cells, 2) + 1)

User-Defined Data Types in Visual Basic 6


Variables of different data types when combined as a
single variable to hold several related informations is
called a User-Defined data type.

A Type statement is used to define a user-defined type


in the General declaration section of a form or module.
User-defined data types can only be private in form
while in standard modules can be public or private. An
example for a user defined data type to hold the
product details is as given below.

Private Type ProductDetails


ProdID as String
ProdName as String
Price as Currency
End Type

The user defined data type can be declared with a


variable using the Dim statement as in any other
variable declaration statement. An array of these user-
defined data types can also be declared. An example to
consolidate these two features is given below.

55
Dim ElectronicGoods as ProductDetails ' One Record
Dim ElectronicGoods(10) as ProductDetails ' An array
of 11 records

A User-Defined data type can be referenced in an


application by using the variable name in the
procedure along with the item name in the Type block.
Say, for example if the text property of a TextBox
namely text1 is to be assigned the name of the
electronic good, the statement can be written as given
below.

[Link] = [Link]

If the same is implemented as an array, then the


statement becomes

[Link] = ElectronicGoods(i).ProdName

User-defined data types can also be passed to


procedures to allow many related items as one
argument.

Sub ProdData( ElectronicGoods as ProductDetails)


[Link] = [Link]
[Link] = [Link]
End Sub

56
Constants, Data Type Conversion, Visual Basic
Built-in Functions

Constants

Constants are named storage locations in memory, the


value of which does not change during program
Execution. They remain the same throughout the
program execution. When the user wants to use a
value that never changes, a constant can be declared
and created. The Const statement is used to create a
constant. Constants can be declared in local, form,
module or global scope and can be public or private as
for variables. Constants can be declared as illustrated
below.

Public Const gravityconstant As Single = 9.81

Predefined Visual Basic Constants

The predefined constants can be used anywhere in the


code in place of the actual numeric values. This makes
the code easier to read and write.

For example consider a statement that will set the


window state of a form to be maximized.

[Link] = 2

57
The same task can be performed using a Visual Basic
constant

[Link] = vbMaximized

Data Type Conversion

Visual Basic functions either to convert a string into


an integer or vice versa and many more conversion
functions. A complete listing of all the conversion
functions offered by Visual Basic is elucidated below.
Conversion
Function
To

Boolean Cbool

Byte Cbyte

Currency Ccur

Date Cdate

Decimals Cdec

Double CDbl

Integer Cint

Long CLng

58
Single CSng

String CStr

Variant Cvar

Error CVErr

A conversion function should always be placed at the


right hand side of the calculation statement.

Visual Basic Built-in Functions

Many built-in functions are offered by Visual Basic


fall under various categories. These functions are
procedures that return a value. The functions fall into
the following basic categories that will be discussed in
the follwing sections at length.

• Date and Time Functions


• Format Function
• String Functions

Date and Time Functions in Visual Basic 6


Not only does Visual Basic let you store date and time
information in the specific Date data type, it also
provides a lot of date- and time-related functions.
These functions are very important in all business

59
applications and deserve an in-depth look. Date and
Time are internally stored as numbers in Visual Basic.
The decimal points represents the time between
0:00:00 and 23:59:59 hours inclusive.

The system's current date and time can be retrieved


using the Now, Date and Time functions in Visual
Basic. The Now function retrieves the date and time,
while Date function retrieves only date and Time
function retrieves only the time.

To display both the date and time together a message


box is displayed use the statement given below.

MsgBox "The current date and time of the system is"


& Now

Here & is used as a concatenation operator to


concentrate the string and the Now function. Selective
portions of the date and time value can be extracted
using the below listed functions.

Function Extracted Portion

Year ( ) Year (Now)

Month ( ) Month (Now)

60
Day ( ) Day (Now)

WeekDay ( ) WeekDay (Now)

Hour ( ) Hour (Now)

Minute ( ) Minute (Now)

Second ( ) Second (Now)

The calculation and conversion functions related to


date and time functions are listed below.
Function Description

DateAdd ( ) Returns a date to which a


specific interval has been
added

DateDiff ( ) Returns a Long data type


value specifying the interval
between the two values

DatePart( ) Returns an Integer containing


the specified part of a given date

DateValue ( ) Converts a string to a Date

TimeValue ( ) Converts a string to a time

DateSerial ( ) Returns a date for specified year,

61
month and day

DateDiff Function

The DateDiff function returns the intervals between


two dates in terms of years, months or days. The
syntax for this is given below.

DateDiff (interval, date1, date2[, firstdayofweek[,


firstweekofyear]])

Format Function

The format function accepts a numeric value and


converts it to a string in the format specified by the
format argument. The syntax for this is given below.

Format (expression[, format[, firstdayofweek[,


firstweekofyear]]])

The Format function syntax has these parts:


Part Description

Expression Required any valid


expression

format Optional. A valid named or


user-defined format

62
expression.

firstdayofweek Optional. A contant that


specifies the first day of the
week.

firstweekofyear Optional. A contant that


specifies the first week of
the year

2.6 Working with controls in Visual Basic 6

This lesson concentrates on Visual Basic controls and


the ways of creating and implementing the. It also
helps us to understand the concept of Control Arrays.
Controls are used to recieve user input and display
output and has its own set of properties, methods and
events. Let us discuss few of these controls in this
lesson.

Creating and Using Controls


A control is an object that can be drawn on a Form
object to enable or enhance user interaction with an
application. Controls have properties that define
aspects their appearance, such as position, size and
colour, and aspects of their behavior, such as their
response to the user input. They can respond to events
initiated by the user or set off by the system. For

63
instance, a code could be written in a CommandButton
control's click event procedure that would load a file
or display a result.

In addition to properties and events, methods can also


be used to manipulate controls from code. For
instance, the move method can be used with some
controls to change their location and size.

Most of the controls provide choices to users that can


be in the form of OptionButton or CheckBox controls,
ListBox entries or ScrollBars to select a value. Let us
discuss these controls by means of a few simple
applications in the following lessons.

Classification of Controls

Visual Basic cojntrols are broadly classified as


standard controls, ActiveX controls and insertable
objects. Standard controls such as CommandButton,
Label and Frame controls are contained inside .EXE
file and are always included in the ToolBox which
cannot be removed. ActiveX controls exist as separate
files with either .VBX or .OCX extension. They
include specialized controls such as;

• MSChart control
• The Communications control
• The Animation control

64
• The ListView control
• An ImageList control
• The Multimedia control
• The Internet Transfer control
• The WinSock control
• The TreeView control
• The SysInfo control
• The Picture Clip control

Some of these objects support OLE Automation,


which allow programming another application's object
from within Visual Basic application.

I would like to stress that knowing how and when to


set the objects' properties is very important as it can
help you to write a good program or you may fail to
write a good program. So, I advice you to spend a lot
of time playing with the objects' properties

Here are some important points about setting up the


properties

• You should set the Caption Property of a


control clearly so that a user knows what to
do with that command. For example, in the
calculator program, all the captions of the
command buttons such as +, - , MC, MR are
commonly found in an ordinary calculator, a

65
user should have no problem in manipulating
the buttons.
• A lot of programmers like to use a
meaningful name for the Name Property may
be because it is easier for them to write and
read the event procedure and easier to debug
or modify the programs later. However, it is
not a must to do that as long as you label your
objects clearly and use comments in the
program whenever you feel necessary
• One more important property is whether the
control is enabled or not
• Finally, you must also considering making
the control visible or invisible at runtime, or
when should it become visible or invisible

TabIndex property of Controls

Visual Basic uses the TabIndex property to determine


the control that would receive the focus next when a
tab key is pressed. Every time a tab key is pressed,
Visual Basic looks at the value of the TabIndex for the
control that has focus and then it scans through the
controls searching for the next highest TabIndex
number. When there are no more controls with higher
TabIndex value, Visual Basic starts all over again with
0 and looks for the first control with TabIndex of 0 or
higher that can accept keyboard input.

66
By default, Visual Basic assigns a tab order to control
as we draw the controls on the Form, except for Menu,
Timer, Data, Image, Line and Shape controls, which
are not included in tab order. At run time, invisible or
disabled controls also cannot receive the focus
although a TabIndex value is given. Setting the
TabIndex property of controls is compulsory in
development environment.

Using TextBox Control In Visual Basic 6

TextBox controls offer a natural way for users to enter


a value in your program. For this reason, they tend to
be the most frequently used controls in the majority of
Windows applications. TextBox controls, which have
a great many properties and events, are also among the
most complex intrinsic controls. In this section, I guide
you through the most useful properties of TextBox
controls and show how to solve some of the problems
that you're likely to encounter.

Setting properties to a TextBox

• Text can be entered into the text box by


assigning the necessary string to the text
property of the control

67
• If the user needs to display multiple lines of
text in a TextBox, set the MultiLine property
to True
• To customize the scroll bar combination on a
TextBox, set the ScrollBars property.
• Scroll bars will always appear on the
TextBox when it's MultiLine property is set
to True and its ScrollBars property is set to
anything except None(0)
• If you set the MultilIne property to True, you
can set the alignment using the Alignment
property. The test is left-justified by default.
If the MultiLine property is et to False, then
setting the Alignment property has no effect.

Run-Time Properties of a TextBox control

The Text property is the one you'll reference most


often in code, and conveniently it's the default
property for the TextBox control. Three other
frequently used properties are these:

• The SelStart property sets or returns the


position of the blinking caret (the insertion
point where the text you type appears). Note
that the blinking cursor inside TextBox and
other controls is named caret, to distinguish it
from the cursor (which is implicitly the
mouse cursor). When the caret is at the

68
beginning of the contents of the TextBox
control, SelStart returns 0; when it's at the
end of the string typed by the user, SelStart
returns the value Len(Text). You can modify
the SelStart property to programmatically
move the caret.
• The SelLength property returns the number
of characters in the portion of text that has
been highlighted by the user, or it returns 0 if
there's no highlighted text. You can assign a
nonzero value to this property to
programmatically select text from code.
Interestingly, you can assign to this property
a value larger than the current text's length
without raising a run-time error.
• The SelText property sets or returns the
portion of the text that's currently selected, or
it returns an empty string if no text is
highlighted. Use it to directly retrieve the
highlighted text without having to query
Text, SelStart, and SelLength properties.
What's even more interesting is that you can
assign a new value to this property, thus
replacing the current selection with your own.
If no text is currently selected, your string is
simply inserted at the current caret position.

When you want to append text to a TextBox control,


you should use the following code (instead of using

69
the concatenation operator) to reduce flickering and
improve performance:

[Link] = Len([Link])
[Link] = StringToBeAdded

One of the typical operations you could find yourself


performing with these properties is selecting the entire
contents of a TextBox control. You often do it when
the caret enters the field so that the user can quickly
override the existing value with a new one, or start
editing it by pressing any arrow key:

Private Sub Text1_GotFocus()


[Link] = 0
' A very high value always does the trick.
[Link] = 9999
End Sub

Always set the SelStart property first and then the


SelLength or SelText properties. When you assign a
new value to the SelStart property, the other two are
automatically reset to 0 and an empty string
respectively, thus overriding your previous settings.

The selected text can be copied to the Clipboard by


using SelText:

70
[Link] text, [format]

In the above syntax, text is the text that has to be


placed into the Clipboard, and format has three
possible values.

[Link] - Conversation information


[Link] - Rich Text Format
[Link] - Text

We can get text from the clipboard using the GetText()


function this way:

[Link] ([format])

The following Figure summarizes the common


TextBox control's properties and methods.

Property/
Description
Method

Properties
Enabled specifies whether user can

71
interact with this control or not
Index Specifies the control array index
If this control is set to True user
Locked can use it else if this control is set
to false the control cannot be used
Specifies the maximum number
of characters to be input. Default
MaxLength value is set to 0 that means user
can input any number of
characters
Using this we can set the shape of
MousePointer the mouse pointer when over a
TextBox
By setting this property to True
Multiline user can have more than one line
in the TextBox
This is to specify mask character
PasswordChar
to be displayed in the TextBox
This to set either the vertical
scrollbars or horizontal scrollbars
ScrollBars to make appear in the TextBox.
User can also set it to both
vertical and horizontal. This
property is used with the
Multiline property.
Text Specifies the text to be displayed

72
in the TextBox at runtime
This is used to display what text
ToolTipIndex
is displayed or in the control
By setting this user can make the
Visible Textbox control visible or
invisible at runtime

Method
SetFocus Transfers focus to the TextBox

Event
procedures
Action happens when the
Change
TextBox changes
Action happens when the
Click
TextBox is clicked
Action happens when the
GotFocus
TextBox receives the active focus
Action happens when the
LostFocus
TextBox loses it focus
Called when a key is pressed
KeyDown
while the TextBox has the focus

73
Called when a key is released
KeyUp
while the TextBox has the focus

VB6 CommandButton and OptionButton Controls


- Visual Basic 6

When compared to TextBox controls, these controls


are really simple. Not only do they expose relatively
few properties, they also support a limited number of
events, and you don't usually write much code to
manage them.

CommandButton Controls in VB6

Using CommandButton controls is trivial. In most


cases, you just draw the control on the form's surface,
set its Caption property to a suitable string (adding an
& character to associate a hot key with the control if
you so choose), and you're finished, at least with user-
interface issues. To make the button functional, you
write code in its Click event procedure, as in this
fragment:

Private Sub Command1_Click()


' Save data, then unload the current form.
Call SaveDataToDisk
Unload Me
End Sub

74
You can use two other properties at design time to
modify the behavior of a CommandButton control.
You can set the Default property to True if it's the
default push button for the form (the button that
receives a click when the user presses the Enter key—
usually the OK or Save button). Similarly, you can set
the Cancel property to True if you want to associate
the button with the Escape key.

The only relevant CommandButton's run-time


property is Value, which sets or returns the state of the
control (True if pressed, False otherwise). Value is
also the default property for this type of control. In
most cases, you don't need to query this property
because if you're inside a button's Click event you can
be sure that the button is being activated. The Value
property is useful only for programmatically clicking a
button:

This fires the button's Click event.


[Link] = True

The CommandButton control supports the usual set of


keyboard and mouse events (KeyDown, KeyPress,
KeyUp, MouseDown, MouseMove, MouseUp, but not
the DblClick event) and also the GotFocus and
LostFocus events, but you'll rarely have to write code
in the corresponding event procedures.

75
Properties of a CommandButton control

• To display text on a CommandButton control,


set its Caption property.
• An event can be activated by clicking on the
CommandButton.
• To set the background colour of the
CommandButton, select a colour in the
BackColor property.
• To set the text colour set the Forecolor
property.
• Font for the CommandButton control can be
selected using the Font property.
• To enable or disable the buttons set the
Enabled property to True or False
• To make visible or invisible the buttons at run
time, set the Visible property to True or
False.
• Tooltips can be added to a button by setting a
text to the Tooltip property of the
CommandButton.
• A button click event is handled whenever a
command button is clicked. To add a click
event handler, double click the button at
design time, which adds a subroutine like the
one given below.

Private Sub Command1_Click( )

76
..................
End Sub

Option Button Controls in VB6

OptionButton controls are also known as radio buttons


because of their shape. You always use OptionButton
controls in a group of two or more because their
purpose is to offer a number of mutually exclusive
choices. Anytime you click on a button in the group, it
switches to a selected state and all the other controls in
the group become unselected.

Preliminary operations for an OptionButton control are


similar to those already described for CheckBox
controls. You set an OptionButton control's Caption
property to a meaningful string, and if you want you
can change its Alignment property to make the control
right aligned. If the control is the one in its group that's
in the selected state, you also set its Valueproperty to
True. (The OptionButton's Value property is a
Boolean value because only two states are possible.)
Value is the default property for this control.

At run time, you typically query the control's Value


property to learn which button in its group has been
selected. Let's say you have three OptionButton
controls, named optWeekly, optMonthly, and

77
optYearly. You can test which one has been selected
by the user as follows:

If [Link] Then
' User prefers weekly frequency.
ElseIf [Link] Then
' User prefers monthly frequency.
ElseIf [Link] Then
' User prefers yearly frequency.
End If

Strictly speaking, you can avoid the test for the last
OptionButton control in its group because all choices
are supposed to be mutually exclusive. But the
approach I just showed you increases the code's
readability.

A group of OptionButton controls is often hosted in a


Frame control. This is necessary when there are other
groups of OptionButton controls on the form. As far as
Visual Basic is concerned, all the OptionButton
controls on a form's surface belong to the same group
of mutually exclusive selections, even if the controls
are placed at the opposite corners of the window. The
only way to tell Visual Basic which controls belong to
which group is by gathering them inside a Frame
control. Actually, you can group your controls within
any control that can work as a container—PictureBox,

78
for example—but Frame controls are often the most
reasonable choice.

Example

Open a new Standard EXE project and the save the


Form as [Link] and save the project as
[Link].

Design the Form as per the following specifications


table.
Object Property Settings
Enter a
Caption
Number
Label
Name
Label1
Text (empty)
TextBox
Name Text1
Caption &Close
CommandButton
Name Command1
Caption &Octal
OptionButton
Name optOct
OptionButton Caption &Hexadecimal

79
Name optHex
Caption &Decimal
OptionButton
Name optDec

The application responds to the following events

• The change event of the TextBox reads the


value and stores it in a form-level numeric
variable.
• The click event of optOct button returns
curretval in octal.
• The click event of the optHex button
curerntval in hexadecimal
• The click event of the optDec button returns
the decimal equivalent of the value held
currentval.

The following code is entered in the general


declarations section of the Form.

Dim currentval as variant

The variable is initialized to 0 by default. The change


event procedure checks to ascertain the number system

80
(Octal, Hexadecimal) that is in effect and then reads in
the number.

Private Sub Text1_Change()


If [Link] = True Then
currentval = Val ("&O" & LTrim ([Link]) & "&")
Elseif [Link] = True Then
currentval = Val (LTrim ([Link]) & "&")
Else
currentval = Val ("&H" & LTrim ([Link]) & "&")
End if
End Sub

The Val function is used to translate string to a number


and can recognize Octal and Hexadecimal strings. The
LTrim function trims the leading blanks in the text.
The following code is entered in the click events of the
OptionButton controls.

Private Sub optOct_Click()


[Link] = Oct(currentval)
End Sub

Private Sub optHex_Click()


[Link] = Hex(currentval)
End Sub

81
Private Sub optDec_Click()
[Link] = Format(currentval)
End Sub

The follwoing code is entered in the click event of teh


Close button.

Private Sub cmdClose_Click()


Unlod Me
End Sub

The Application is run by pressing F5 or clicking on


the Run icon in the tool bar. By pressing the Exit
button the program is terminated.

Using ListBox and ComboBox Controls In Visual


Basic 6
ListBox and ComboBox controls present a set of
choices that are displayed vertically in a column. If the
number of items exceed the value that be displayed,
scroll bars will automatically appear on the control.
These scroll bars can be scrolled up and down or left
to right through the list.

The following Fig lists some of the common


ComboBox properties and methods.
Property/Method Description

82
Properties
By setting this property to
True or False user can decide
Enabled
whether user can interact
with this control or not
Specifies the Control array
Index
index
String array. Contains the
strings displayed in the drop-
List
down list. Starting array
index is 0.
Integer. Contains the number
ListCount
of drop-down list items
Integer. Contains the index
of the selected ComboBox
ListIndex
item. If an item is not
selected, ListIndex is -1
Boolean. Specifies whether
Locked user can type or not in the
ComboBox
Integer. Specifies the shape
of the mouse pointer when
MousePointer
over the area of the
ComboBox
Integer. Index of the last item
NewIndex
added to the ComboBox. If

83
the ComboBox does not
contain any items ,
NewIndex is -1
Boolean. Specifies whether
Sorted the ComboBox's items are
sorted or not.
Integer. Specifies the style of
Style
the ComboBox's appearance
Boolean. Specifies whether
TabStop ComboBox receives the
focus or not.
String. Specifies the selected
Text
item in the ComboBox
String. Specifies what text is
ToolTipIndex displayed as the ComboBox's
tool tip
Boolean. Specifies whether
Visible ComboBox is visible or not
at run time
Methods
Add an item to the
AddItem
ComboBox
Removes all items from the
Clear
ComboBox
RemoveItem Removes the specified item

84
from the ComboBox
Transfers focus to the
SetFocus
ComboBox
Event Procedures
Called when text in
Change
ComboBox is changed
Called when the ComboBox
DropDown
drop-down list is displayed
Called when ComboBox
GotFocus
receives the focus
Called when ComboBox
LostFocus
loses it focus

Adding items to a List

It is possible to populate the list at design time or run


time

Design Time : To add items to a list at design time,


click on List property in the property box and then add
the items. Press CTRL+ENTER after adding each item
as shown below.

85
Run Time : The AddItem method is used to add items
to a list at run time. The AddItem method uses the
following syntax.

[Link], Index

The item argument is a string that represents the text to


add to the list

The index argument is an integer that indicates where


in the list to add the new item. Not giving the index is
not a problem, because by default the index is
assigned.

Following is an example to add item to a combo box.


The code is typed in the Form_Load event

Private Sub Form_Load()

86
[Link] 1
[Link] 2
[Link] 3
[Link] 4
[Link] 5
[Link] 6

End Sub

Removing Items from a List

The RemoveItem method is used to remove an item


from a list. The syntax for this is given below.

[Link] index

The following code verifies that an item is selected in


the list and then removes the selected item from the
list.

Private Sub cmdRemove_Click()


If [Link] > -1 Then
[Link] List1. ListIndex
End If
End Sub

87
Sorting the List

The Sorted property is set to True to enable a list to


appear in alphanumeric order and False to display the
list items in the order which they are added to the list.

Using the ComboBox

A ComboBox combines the features of a TextBox and


a ListBox. This enables the user to select either by
typing text into the ComboBox or by selecting an item
from the list. There are three types of ComboBox
styles that are represented as shown below.

Dropdown Simple combo


Dropdown list
combo

• Dropdown Combo (style 0)


• Simple Combo (style 1)
• Dropdown List (style 2)

The Simple Combo box displays an edit area with an


attached list box always visible immediately below the

88
edit area. A simple combo box displays the contents of
its list all the time. The user can select an item from
the list or type an item in the edit box portion of the
combo box. A scroll bar is displayed beside the list if
there are too many items to be displayed in the list box
area.

The Dropdown Combo box first appears as only an


edit area with a down arrow button at the right. The
list portion stays hidden until the user clicks the down-
arrow button to drop down the list portion. The user
can either select a value from the list or type a value in
the edit area.

The Dropdown list combo box turns the combo box


into a Dropdown list box. At run time , the control
looks like the Dropdown combo box. The user could
click the down arrow to view the list. The difference
between Dropdown combo & Dropdown list combo is
that the edit area in the Dropdown list combo is
disabled. The user can only select an item and cannot
type anything in the edit area. Anyway this area
displays the selected item.

Example

This example is to Add , Remove, Clear the list of


items and finally close the application.

89
• Open a new Standard EXE project is opened
an named the Form as [Link] and save
the project as [Link]
• Design the application as shown below.
Object Property Settings
Caption ListBox
Form
Name frmListBox
Text (empty)
TextBox
Name txtName
Label Caption Enter a name
ListBox Name lstName
Caption
Name Amount
lblName Entered
Label
Name lblAmount
Caption
(empty)
Name
Label lblDisplay
Border
1 Fixed Single
Style
Caption Add
CommandButton
Name cmdAdd
CommandButton Caption Remove

90
Name cmdRemove
Caption Clear
CommandButton
Name cmdClear
Caption Exit
CommandButton
Name cmdExit

The following event procedures are entered for the


TextBox and CommandButton controls.

Private Sub txtName_Change()


If (Len([Link]) > 0) Then 'Enabling the Add

91
button
'if atleast one character
'is entered
[Link] = True
End If
End Sub

Private Sub cmdAdd_Click()


[Link] [Link] 'Add the entered the
characters to the list box

[Link] = "" 'Clearing the text box

[Link] 'Get the focus back to the


'text box

[Link] = [Link] 'Display the


number of items in the list box

[Link] = False ' Disabling the Add button

End Sub

The click event of the Add button adds the text to the
list box that was typed in the Text box. Then the text
box is cleared and the focus is got to the text box. The
number of entered values will is increased according
to the number of items added to the listbox.

92
Private Sub cmdClear_Click()
[Link]
[Link] = [Link]
End Sub

Private Sub cmdExit_Click()


Unload Me
End Sub

Private Sub cmdRemove_Click()


Dim remove As Integer

remove = [Link] 'Getting the index

If remove >= 0 Then 'make sure an item is selected


'in the list box

[Link] remove 'Remove item from the


list box

[Link] = [Link] 'Display the


number of items
'in the listbox

End If

End Sub

93
Remove button removes the selected item from the list
as soon as you pressed the Remove button. The
number of items is decreased in the listbox and the
value is displayed in the label.

The code for the clear button clears the listbox when
you press it. And the number of items shown in the
label becomes 0.

VB ScrollBar - Using ScrollBar Control In Visual


Basic 6 (VB6)

The ScrollBar is a commonly used control, which


enables the user to select a value by positioning it at
the desired location. It represents a set of values. The
Min and Max property represents the minimum and
maximum value. The value property of the ScrollBar
represents its current value, that may be any integer
between minimum and maximum values assigned.

The HScrollBar and the VScrollBar controls are


perfectly identical, apart from their different
orientation. After you place an instance of such a
control on a form, you have to worry about only a few
properties: Min and Max represent the valid range of
values, SmallChange is the variation in value you get
when clicking on the scroll bar's arrows, and
LargeChange is the variation you get when you click

94
on either side of the scroll bar indicator. The default
initial value for those two properties is 1, but you'll
probably have to change LargeChange to a higher
value. For example, if you have a scroll bar that lets
you browse a portion of text, SmallChange should be 1
(you scroll one line at a time) and LargeChange should
be set to match the number of visible text lines in the
window.

The most important run-time property is Value, which


always returns the relative position of the indicator on
the scroll bar. By default, the Min value corresponds
to the leftmost or upper end of the control:

' Move the indicator near the top (or left) arrow.
[Link] = [Link]
' Move the indicator near the bottom (or right) arrow.
[Link] = [Link]

While this setting is almost always OK for horizontal


scroll bars, you might sometimes need to reverse the
behavior of vertical scroll bars so that the zero is near
the bottom of your form. This arrangement is often
desirable if you want to use a vertical scroll bar as a
sort of slider. You obtain this behavior by simply
inverting the values in the Min and Max properties. (In
other words, it's perfectly legal for Min to be greater
than Max.)

95
There are two key events for scrollbar controls: the
Change event fires when you click on the scroll bar
arrows or when you drag the indicator; the Scroll
event fires while you drag the indicator. The reason for
these two distinct possibilities is mostly historical.
First versions of Visual Basic supported only the
Change event, and when developers realized that it
wasn't possible to have continuous feedback when
users dragged the indicator, Microsoft engineers added
a new event instead of extending the Change event. In
this way, old applications could be recompiled without
unexpected changes in their behavior. At any rate, this
means that you must often trap two distinct events:

' Show the current scroll bar's value.


Private VScroll1_Change()
[Link] = [Link]
End Sub
Private VScroll1_Scroll()
[Link] = [Link]
End Sub

The example shown in the following figure uses three


VScrollBar controls as sliders to control the individual
RGB (red, green, blue) components of a color. The
three scroll bars have their Min property set to 255 and
their Max property set to 0, while their SmallChange is
1 and LargeChange is 16. This example is also a
moderately useful program in itself because you can

96
select a color and then copy its numeric value to the
clipboard and paste it in your application's code as a
decimal value, a hexadecimal value, or an RGB
function.

Use scrollbar controls to visually create colors.

Scrollbar controls can receive the input focus, and in


fact they support both the TabIndex and TabStop
properties. If you don't want the user to accidentally
move the input focus on a scrollbar control when he or
she presses the Tab key, you must explicitly set its
TabStop property to False. When a scrollbar control
has the focus, you can move the indicator using the

97
Left, Right, Up, Down, PgUp, PgDn, Home, and End
keys. For example, you can take advantage of this
behavior to create a read-only TextBox control with a
numeric value that can be edited only through a tiny
companion scroll bar. This scroll bar appears to the
user as a sort of spin button, as you can see in the
figure below. To make the trick work, you need to
write just a few lines of code:

Private Sub Text1_GotFocus()


' Pass the focus to the scroll bar.
[Link]
End Sub
Private Sub VScroll1_Change()
' Scroll bar controls the text box value.
[Link] = [Link]
End Sub

Scrollbar controls are even more useful for building


scrolling forms, like the one displayed in Figure 3-15.

98
To be certain, scrolling forms aren't the most
ergonomic type of user interface you can offer to your
customers: If you have that many fields in a form, you
should consider using a Tab control, child forms, or
some other custom interface. Sometimes, however,
you badly need scrollable forms, and in this situation
you are on your own because Visual Basic forms don't
support scrolling.

Fortunately, it doesn't take long to convert a regular


form into a scrollable one. You need a couple of
scrollbar controls, plus a PictureBox control that you
use as the container for all the controls on the form,
and a filler control—a CommandButton, for
example—that you place in the bottom-right corner of
the form when it displays the two scroll bars. The
secret to creating scrollable forms is that you don't
move all the child controls one by one. Instead, you
place all the controls in the PictureBox control (named
picCanvas in the following code), and you move it
when the user acts on the scroll bar:

Sub MoveCanvas()
[Link] -[Link], -[Link]
End Sub

In other words, to uncover the portion of the form near


the right border, you assign a negative value to the
PictureBox's Left property, and to display the portion

99
near the form's bottom border you set its Top property
to a negative value. It's really that simple. You do this
by calling the MoveCanvas procedure from within the
scroll bars' Change and Scroll events. Of course, it's
critical that you write code in the Form_Resize event,
which makes a scroll bar appear and disappear as the
form is resized, and that you assign consistent values
to Max properties of the scrollbar controls:

' size of scrollbars in twips


Const SB_WIDTH = 300 ' width of vertical scrollbars
Const SB_HEIGHT = 300 ' height of horizontal
scrollbars

Private Sub Form_Resize()


' Resize the scroll bars along the form.
[Link] 0, ScaleHeight - SB_HEIGHT,
ScaleWidth - SB_WIDTH
[Link] ScaleWidth - SB_WIDTH, 0,
SB_WIDTH, _
ScaleHeight - SB_HEIGHT
[Link] ScaleWidth - SB_WIDTH,
ScaleHeight - SB_HEIGHT, _
SB_WIDTH, SB_HEIGHT

' Put these controls on top.


[Link]
[Link]

100
[Link]
[Link] = 0

' A click on the arrow moves one pixel.


[Link] = ScaleX(1, vbPixels,
vbTwips)
[Link] = ScaleY(1, vbPixels,
vbTwips)
' A click on the scroll bar moves 16 pixels.
[Link] = [Link] * 16
[Link] = [Link] * 16

' If the form is larger than the picCanvas picture box,


' we don't need to show the corresponding scroll bar.
If ScaleWidth < [Link] + SB_WIDTH Then
[Link] = True
[Link] = [Link] + SB_WIDTH -
ScaleWidth
Else
[Link] = 0
[Link] = False
End If
If ScaleHeight < [Link] + SB_HEIGHT
Then
[Link] = True
[Link] = [Link] + SB_HEIGHT -
ScaleHeight
Else
[Link] = 0

101
[Link] = False
End If
' Make the filler control visible only if necessary.
[Link] = ([Link] Or
[Link])
MoveCanvas
End Sub

Working with scrollable forms at design time isn't


comfortable. I suggest that you work with a
maximized form and with the PictureBox control sized
as large as possible. When you're finished with the
form interface, resize the PictureBox control to the
smallest area that contains all the controls, and then
reset the form's WindowState property to 0-Normal.

Control Arrays in Visual Basic 6


A control array is a group of controls that share the
same name type and the same event procedures.
Adding controls with control arrays uses fewer
resources than adding multiple control of same type at
design time.

A control array can be created only at design time, and


at the very minimum at least one control must belong
to it. You create a control array following one of these
three methods:

102
• You create a control and then assign a
numeric, non-negative value to its Index
property; you have thus created a control
array with just one element.
• You create two controls of the same class and
assign them an identical Name property.
Visual Basic shows a dialog box warning you
that there's already a control with that name
and asks whether you want to create a control
array. Click on the Yes button.
• You select a control on the form, press
Ctrl+C to copy it to the clipboard, and then
press Ctrl+V to paste a new instance of the
control, which has the same Name property
as the original one. Visual Basic shows the
warning mentioned in the previous bullet.

Control arrays are one of the most interesting features


of the Visual Basic environment, and they add a lot of
flexibility to your programs:

• Controls that belong to the same control array


share the same set of event procedures; this
often dramatically reduces the amount of
code you have to write to respond to a user's
actions.
• You can dynamically add new elements to a
control array at run time; in other words, you

103
can effectively create new controls that didn't
exist at design time.
• Elements of control arrays consume fewer
resources than regular controls and tend to
produce smaller executables. Besides, Visual
Basic forms can host up to 256 different
control names, but a control array counts as
one against this number. In other words,
control arrays let you effectively overcome
this limit.

The importance of using control arrays as a means of


dynamically creating new controls at run time is
somewhat reduced in Visual Basic 6, which has
introduced a new and more powerful capability.

Don't let the term array lead you to think control array
is related to VBA arrays; they're completely different
objects. Control arrays can only be one-dimensional.
They don't need to be dimensioned: Each control you
add automatically extends the array. The Index
property identifies the position of each control in the
control array it belongs to, but it's possible for a
control array to have holes in the index sequence. The
lowest possible value for the Index property is 0. You
reference a control belonging to a control array as you
would reference a standard array item:

Text1(0).Text = ""

104
Sharing Event Procedures

Event procedures related to items in a control array are


easily recognizable because they have an extra Index
parameter, which precedes all other parameters. This
extra parameter receives the index of the element that's
raising the event, as you can see in this example:

Private Sub Text1_KeyPress(Index As Integer,


KeyAscii As Integer)
MsgBox "A key has been pressed on Text1(" & Index
& ") control"
End Sub

The fact that multiple controls can share the same set
of event procedures is often in itself a good reason to
create a control array. For example, say that you want
to change the background color of each of your
TextBox controls to yellow when it receives the input
focus and restore its background color to white when
the user clicks on another field:

Private Sub Text1_GotFocus(Index As Integer)


Text1(Index).BackColor = vbYellow
End Sub
Private Sub Text1_LostFocus(Index As Integer)
Text1(Index).BackColor = vbWhite
End Sub

105
Control arrays are especially useful with groups of
OptionButton controls because you can remember
which element in the group has been activated by
adding one line of code to their shared Click event.
This saves code when the program needs to determine
which button is the active one:

' A module-level variable


Dim optFrequencyIndex As Integer

Private Sub optFrequency_Click(Index As Integer)


' Remember the last button selected.
optFrequencyIndex = Index
End Sub

Creating Controls at Run Time

Control arrays can be created at run time using the


statements

• Load object (Index %)


• Unload object (Index %)

Where object is the name of the control to add or


delete from the control array. Index % is the value of
the index in the array. The control array to be added
must be an element of the existing array created at
design time with an index value of 0. When a new
element of a control array is loaded, most of the

106
property settings are copied from the lowest existing
element in the array.

Following example illustrates the use of the control


array.

* Open a Standard EXE project and save the Form as


[Link] and save the Project as [Link].

* Design the form as shown below.


Object Property Setting
Caption Calculator
Form
Name frmCalculator
Caption 1

CommandButton Name cmd

Index 0
Caption 2

CommandButton Name cmd

Index 1
CommandButton Caption 3

107
Name cmd

Index 2
Caption 4

CommandButton Name cmd

Index 3
Caption 5

CommandButton Name cmd

Index 4
Caption 6

CommandButton Name cmd

Index 5
Caption 7

CommandButton Name cmd

Index 6
CommandButton Caption 8

108
Name cmd

Index 7
Caption 9

CommandButton Name cmd

Index 8
Caption 0

CommandButton Name cmd

Index 10
Caption .

CommandButton Name cmd

Index 11
Caption AC
CommandButton
Name cmdAC
Caption +
CommandButton
Name cmdPlus

109
Caption -
CommandButton
Name cmdMinus
Caption *
CommandButton
Name cmdMultiply
Caption /
CommandButton
Name cmdDivide
Caption +/-
CommandButton
Name cmdNeg
Name txtDisplay
TextBox
Text ( empty )
Caption =
CommandButton
Name cmdEqual

110
The following variables are declared inside the general
declaration

Dim Current As Double


Dim Previous As Double
Dim Choice As String
Dim Result As Double

The following code is entered in the cmd_Click( )


(Control Array) event procedure

Private Sub cmd_Click(Index As Integer)


[Link] = [Link] &
cmd(Index).Caption
'&is the concatenation operator

111
Current = Val([Link])
End Sub

The following code is entered in the cmdAC_Click ( )


event procedure

Private Sub cmdAC_Click()


Current = Previous = 0
[Link] = ""
End Sub

The below code is entered in the cmdNeg_Click( )


procedure

Private Sub cmdNeg_Click()


Current = -Current
[Link] = Current
End Sub

The following code is entered in the click events of the


cmdPlus, cmdMinus, cmdMultiply, cmdDevide
controls respectively.

Private Sub cmdDevide_Click()


[Link] = ""
Previous = Current
Current = 0

112
Choice = "/"
End Sub

Private Sub cmdMinus_Click()


[Link] = ""
Previous = Current
Current = 0
Choice = "-"
End Sub

Private Sub cmdMultiply_Click()


[Link] = ""
Previous = Current
Current = 0
Choice = "*"
End Sub

Private Sub cmdPlus_Click()


[Link] = ""
Previous = Current
Current = 0
Choice = "+"
End Sub

To print the result on the text box, the following code


is entered in the cmdEqual_Click ( ) event procedure.

Private Sub cmdEqual_Click()

113
Select Case Choice

Case "+"
Result = Previous + Current
[Link] = Result
Case "-"
Result = Previous - Current
[Link] = Result
Case "*"
Result = Previous * Current
[Link] = Result
Case "/"
Result = Previous / Current
[Link] = Result
End Select

Current = Result

End Sub

Save and run the project. On clicking digits of user's


choice and an operator button, the output appears.

Iterating on the Items of a Control Array

Control arrays often let you save many lines of code


because you can execute the same statement, or group
of statements, for every control in the array without
having to duplicate the code for each distinct control.

114
For example, you can clear the contents of all the
items in an array of TextBox controls as follows:

For i = [Link] To [Link]


txtFields(i).Text = ""
Next

Here you're using the LBound and UBound methods


exposed by the control array object, which is an
intermediate object used by Visual Basic to gather all
the controls in the array. In general, you shouldn't use
this approach to iterate over all the items in the array
because if the array has holes in the Index sequence an
error will be raised. A better way to loop over all the
items of a control array is using the For Each
statement:

Dim txt As TextBox


For Each txt In txtFields
[Link] = ""
Next

A third method exposed by the control array object,


Count, returns the number of elements it contains. It
can be useful on several occasions (for example, when
removing all the controls that were added dynamically
at run time):

115
' This code assumes that txtField(0) is the only control
that was
' created at design time (you can't unload it at run
time).
Do While [Link] > 1
Unload txtFields([Link])
Loop

Arrays of Menu Items

Control arrays are especially useful with menus


because arrays offer a solution to the proliferation of
menu Click events and, above all, permit you to create
new menus at run time. An array of menu controls is
conceptually similar to a regular control array, only
you set the Index property to a numeric (non-negative)
value in the Menu Editor instead of in the Properties
window.

There are some limitations, though: All the items in an


array of menu controls must be adjacent and must
belong to the same menu level, and their Index
properties must be in ascending order (even though
holes in the sequence are allowed). This set of
requirements severely hinders your ability to create
new menu items at run time. In fact, you can create
new menu items in well-defined positions of your
menu hierarchy—namely, where you put a menu item

116
with a nonzero Index value—but you can't create new
submenus or new top-level menus.

Now that you have a thorough understanding of how


Visual Basic's forms and controls work, you're ready
to dive into the subtleties of the Visual Basic for
Applications (VBA) language.

117
UNIT - II

WORKING WITH MENUS IN VISUAL BASIC


Combinational Logic Circuits: Boolean algebra –
Karnaugh map –Canonical form 1 –Construction
and properties –Implicants –Don‘t care
combinations -Product of sum, Sum of products,
simplifications. Sequential circuits: Flip-Flops:
RS, D, JK, and T -Multiplexers –Demultiplexers
–Decoder Encoder –shift registers-Counters

Windows applications provide groups of related


commands in Menus. These commands depend on the
application, but some-such as Open and Save are
frequently found in applications. Menus are intrinsic
controls, and as such they deserve a place in this
chapter. On the other hand, menus behave differently
from other controls. For example, you don't drop menu
items on a form from the Toolbox; rather, you design
them in the Menu Editor window, as you can see in the
figur below. You invoke this tool from the Menu
Editor button on the standard toolbar or by pressing
the Ctrl+E shortcut key. There's also a Menu Editor

118
command in the Tools menu, but you probably won't
use it often.

Visual Basic provides an easy way to create menus


with the modal Menu Editor dialog. The below dialog
is displayed when the Menu Editor is selected in the
Tool Menu. The Menu Editor command is grayed
unless the form is visible. And also you can display
the Menu Editor window by right clicking on the Form
and selecting Menu Editor.

Basically, each menu item has a Caption property


(possibly with an embedded & character to create an
access key) and a Name. Each item also exposes three
Boolean properties, Enabled, Visible, and Checked,
which you can set both at design time and at run time.
At design time, you can assign the menu item a
shortcut key so that your end users don't have to go
through the menu system each time they want to
execute a frequent command. (Do you really like
pulling down the Edit menu any time you need to clear
some text or copy it to the Clipboard?) The assigned
shortcut key can't be queried at run time, much less
modified.

Building a menu is a simple, albeit more tedious, job:


You enter the item's Caption and Name, set other
properties (or accept the default values for those
properties), and press Enter to move to the next item.

119
When you want to create a submenu, you press the
Right Arrow button (or the Alt+R hot key). When you
want to return to work on top-level menus—those
items that appear in the menu bar when the application
runs—you click the Left Arrow button (or press
Alt+L). You can move items up and down in the
hierarchy by clicking the corresponding buttons or the
hot keys Alt+U and Alt+B, respectively.

You can create up to five levels of submenus (six


including the menu bar), which are too many even for
the most patient user. If you find yourself working
with more than three menu levels, think about trashing
your specifications and redesigning your application
from the ground up.

You can insert a separator bar using the hypen (-)


character for the Caption property. But even these
separator items must be assigned a unique value for
the Name property, which is a real nuisance. If you
forget to enter a menu item's Name, the Menu Editor
complains when you decide to close it. The convention
used in this book is that all menu names begin with the
three letters mnu.

3.1 An expanded Menu Editor window.

120
An expanded menu

One of the most annoying defects of the Menu Editor


tool is that it doesn't permit you to reuse the menus
you have already written in other applications. It
would be great if you could open another instance of

121
the Visual Basic IDE, copy one or more menu items to
the clipboard, and then paste those menu items in the
application under development. You can do that with
controls and with pieces of code, but not with menus!
The best thing you can do in Visual Basic is load the
FRM file using an editor such as Notepad, find the
portion in the file that corresponds to the menu you're
interested in, load the FRM file you're developing (still
in Notepad), and paste the code there. This isn't the
easiest operation, and it's also moderately dangerous:
If you paste the menu definition in the wrong place,
you could make your FRM form completely
unreadable. Therefore, always remember to make
backup copies of your forms before trying this
operation.

Better news is that you can add a finished menu to a


form in your application with just a few mouse clicks.
All you have to do is activate the Add-In Manager
from the Add-Ins menu, choose the VB 6 Template
Manager, and tick the Loaded/Unloaded check box.
After you do that, you'll find three new commands in
the Tools menu: Add Code Snippet, Add Menu, and
Add Control Set. Visual Basic 6 comes with a few
menu templates, as you can see in the following
figure, that you might find useful as a starting point for
building your own templates. To create your menu
templates, you only have to create a form with the
complete menu and all the related code and then store
this form in the \Templates\Menus directory. (The

122
complete path, typically c:\Program Files\Microsoft
Visual Studio\VB98\Template, can be found in the
Environment tab of the Options dialog box on the
Tools menu. The Template Manager was already
available with Visual Basic 5, but it had to be installed
manually and relatively few programmers were aware
of its existence.

The Template Manager in action

The programmer can create menu control arrays. The


Index TextBox specifies the menu's index in the
control array.

123
The Menu Editor dialog also provides several
CheckBoxes to control the appearance of the Menu.

Checked : This is unchecked by default and allows the


programmer the option of creating a checked menu
item( a menu item that act as a toggle and displays a
check mark when selected. The following is a Check
Menu items.

Enabled : specifies whether a menu is disabled or not.


If you see a disabled command in a menu that means
that feature is not available. The Visible checkbox
specifies whether the menu is visible or not.

To add commands to the Form's menu bar, enter a


caption and a name for each command. As soon as you
start typing the command's caption, it also appears in a
new line in the list at the bottom of the Menu Editor
window. To add more commands click Enter and type
the Caption and the Name.

124
3.2 Creating Menus

Open a new Project and save the form as [Link]


and save the project as [Link].

Choose Tools ››› Menu Editor and type the menu


items as shown below.

Caption Name
File mnuFile
Open mnuOpen
Save mnuSave
Exit mnuExit
Edit mnuEdit
Copy mnuCopy
Cut mnuCut
Paste mnuPaste

125
Run the application by pressing F5. You can see that
you can select a menu. There are other Menus in
Visual Basic 6

• Accessing Menus at Run Time


• Pop-Up Menus

126
[Link] EVENTS IN VISUAL BASIC 6

Visual Basic responds to various mouse events, which


are recognized by most of the controls. The main
events are MouseDown, MouseUp and MouseMove.
MouseDown occurs when the user presses any mouse
button and MouseUp occurs when the user releases
any mouse button. These events use the arguments
button, Shift, X, Y and they contain information about
the mouse's condition when the button is clicked.

The first argument is an integer called Button. The


value of the argument indicates whether the left, right

127
or middle mouse button was clicked. The second
argument in an integer called shift. The value of this
argumnet indicates whether the mouse button was
clicked simultaneously with the Shift key, Ctrl key or
Alt key. The third and fourth arguments X and Y are
the coordinates of the mouse location at the time the
mouse button was clicked. As the Form_MouseDown(
) is executed automatically whenever the mouse button
is clicked inside the Form's area the X, Y co-ordinates
are referenced to the form.

4.1 Positioning a control

MouseDown is the commonly used event and it is


combined wiyth the move method to move an Image
control to different locations in a Form. The following
application illustrates the movement of objects
responding to move events. it makes use of two
OptionButton Controls, two image controls and a
CommandButton. The application is designed in such
a way that when an OptionButton is selected, the
corresponding image control is placed anywhere in the
form whenever it is clicked.

Open a new standard EXE project and save the Form


as [Link] and save the project as [Link] Design
the Form as shown below.
Object Property Setting

128
Form Caption MouseDown

Name frmMouseDown
Credit card is
OptionButton Caption
selected
Name
optCredit
Value
True
OptionButton Caption Cash is selected

Name optCash
Image Name imgCredit

Picture c:/[Link]
Image Name imgCash

Picture c:/[Link]

The follwoing code is entered in the general


declarations section of the Form.
Option Explicit

The following code is entered in the


Form_MouseDown( ) event

129
Private Sub Form_MouseDown(Button As Integer,
Shift As Integer, X As Single, Y As Single)
If optCredit = True Then
[Link] X, Y
Else
[Link] X, Y
End If
End Sub

Run the application by keying in F5. You can notice


that when the mouse is clicked on the form
somewhere, the selected image moves to that clicked
location. This is shown in the below figure.

130
4.2 Dialog Boxes
Modal and Modeless Dialog Boxes

Modal Dialog Boxes

There are two types of dialog boxes: modal and


modeless.

A Modal dialog box is one that the user must first


close in order to have access to any other framed
window or dialog box of the same application. One of
the scenarios in which you use a dialog box is to create
an application that is centered around one. In this case,
if either there is no other form or dialog box in your
application or all the other forms or dialog boxes
depend on this central dialog box, it must be created as
modal. Such an application is referred to as dialog-
based.

Some applications require various dialog boxes to


complete their functionality. When in case, you may
need to call one dialog box from another and display it
as modal.

131
4.3 The Multiple Document Interface (MDI) in
Visual Basic 6
The Multiple Document Interface (MDI) was designed
to simplify the exchange of information among
documents, all under the same roof. With the main
application, you can maintain multiple open windows,
but not multiple copies of the application. Data
exchange is easier when you can view and compare
many documents simultaneously.

You almost certainly use Windows applications that


can open multiple documents at the same time and
allow the user to switch among them with a mouse-
click. Multiple Word is a typical example, although
most people use it in single document mode. Each
document is displayed in its own window, and all
document windows have the same behavior. The main
Form, or MDI Form, isn't duplicated, but it acts as a
container for all the windows, and it is called the
parent window. The windows in which the individual
documents are displayed are called Child windows.

An MDI application must have at least two Form, the


parent Form and one or more child Forms. Each of
these Forms has certain properties. There can be many
child forms contained within the parent Form, but
there can be only one parent Form.

132
The parent Form may not contain any controls. While
the parent Form is open in design mode, the icons on
the ToolBox are not displayed, but you can't place any
controls on the Form. The parent Form can, and
usually has its own menu.

To create an MDI application, follow these steps:

1. Start a new project and then choose Project


>>> Add MDI Form to add the parent Form.
2. Set the Form's caption to MDI Window
3. Choose Project >>> Add Form to add a SDI
Form.
4. Make this Form as child of MDI Form by
setting the MDI Child property of the SDI
Form to True. Set the caption property to
MDI Child window.

Visual Basic automatically associates this new Form


with the parent Form. This child Form can't exist
outside the parent Form; in the words, it can only be
opened within the parent Form.

133
Parent and Child Menus

MDI Form cannot contain objects other than child


Forms, but MDI Forms can have their own menus.
However, because most of the operations of the
application have meaning only if there is at least one
child Form open, there's a peculiarity about the MDI
Forms. The MDI Form usually has a menu with two
commands to load a new child Form and to quit the
application. The child Form can have any number of
commands in its menu, according to the application.
When the child Form is loaded, the child Form's menu
replaces the original menu on the MDI Form

Following example illustrates the above explanation.

* Open a new Project and name the Form as [Link]


and save the Project as [Link]

134
* Design a menu that has the following structure.

<> MDIMenu Menu caption

• MDIOpen opens a new child Form


• MDIExit terminates the application

* Then design the following menu for the child Form

<> ChildMenu Menu caption

• Child Open opens a new child Form


• Child Save saves the document in the active
child Form
• Child Close Closes the active child Form

At design time double click on MDI Open and add the


following code in the click event of the open menu.

[Link]

And so double click on MDI Exit and add the


following code in the click event

End

135
Double click on Child Close and enter the following
code in the click event

Unload Me

Before run the application in the project properties set


MDI Form as the start-up Form. Save and run the
application. Following output will be displayed.

And as soon as you click MDI Open you can notice


that the main menu of the MDI Form is replaced with
the Menu of the Child Form. The reason for this
behavior should be obvious. The operation available
through the MDI Form are quite different from the
operations of the child window. Moreover, each child
Form shouldn't have it's own menu.

136
Graphical Mouse Application In Visual Basic 6
The mouse events can be combined with graphics
methods and any number of customized drawing or
paint applications can be created. The following
application combines MouseMove and MouseDown
events, and illustrates a drawing program.

Open a new Standard EXE project and save the Form


as [Link] and save the Project as [Link]. Name
the caption of the as Drawing. Add command button
control and name the caption of it as Clear

Enter the following code in the Form_MouseDown ( )


procedure, Form_MouseMove ( ) procedure and
cmdClear_Click ( ) procedures respectively.

Private Sub cmdClear_Click()


[Link]
End Sub

Private Sub Form_MouseDown(Button As Integer,


Shift As Integer, X As Single, Y As Single)
[Link] = X
[Link] = Y
End Sub

Private Sub Form_MouseMove(Button As Integer,


Shift As Integer, X As Single, Y As Single)
If Button = 1 Then

137
Line ([Link], [Link])-(X, Y)
End If
End Sub

Button value 1 indicates that the left mouse button is


clicked. The code written in the MouseDown event
changes the CurrentX and CurrentY to the coordinates
where the mouse button was just clicked.

Run the application. You can notice that when the


mouse is clicked and moved in the Form a line is
drawn corresponding to the mouse movement.
Following figure illustrates the combined action of
MouseDown and MouseMove.

138
The program uses two graphics related Visual Basic
concepts, the Line method and the CurrentX and
CurrentY properties. Line method is preferred to draw
a line in a Form. The following statement draws a line
from the coordinates X = 2500, Y = 2000, X = 5000,
Y = 5500

Line (2500, 2000) - (5000, 5500)

The CurrentX and CurrentY properties are not visible


in the properties window of the Form because it
cannot be set at the design time. After using the Line
method to draw a line in a Form, Visual Basic
automatically assigns the coordinate of the line's end
point to the CurrentX and CurrentY properties of the
Form on which the line is drawn.

MouseMove application

Visual Basic does not generate a MouseMove event


for every pixel the mouse moves over and a limited
number of mouse messages are generated per second
by the operating environment. The following
application illustrates how often the
Form_MouseMove ( ) event is executed.

Open a new standard EXE project and save the form


as [Link] and save the Project as
[Link]. Place a CommandButton control

139
and name the caption as Clear and set the name as
cmdClear.

The following code is entered in the cmdClear_Click (


) and Form_MouseMove ( ) events respectively.

Private Sub cmdClear_Click()


[Link]
End Sub

Private Sub Form_MouseMove(Button As Integer,


Shift As Integer, X As Single, Y As Single)
Circle (X, Y), 70
End Sub

The above procedure simply draws small circles at the


mouse's current location using the Circle method. The
parameter x, y represent the centre of the circle, and
the second parameter represents the radius of the
circle.

Save the application and run. You can notice that


when the mouse is moved inside the Form, circles are
drwan along the path of the mouse movement as
shown in below figure. And also you can notice the
circles are widely spaced when the mouse is moved
quickly. Each small circle is an indication that the
MouseMove event occured and the Form_MouseMove
( ) procedure was executed.

140
Introduction

Using Microsoft's FlexGrid control


([Link]) you can create utilities to
display, filter, edit, validate and update your data. For
example, such utilities could include:

1. data entry & validation


2. high level reports
3. ported spreadsheet macro applications
retaining cell layout & format

Included in VB4(32-bit), VB5 and VB6, are several


grid-orientated controls aimed at managing rows and

141
columns of data, however one of the most versatile,
hence its name, is the FlexGrid. Most of the other grid
objects are specifically designed for data binding,
whereas the FlexGrid has many collections of
properties, methods and events that lend themselves to
several environments in addition to just data-binding.

One of the most powerful applications of the FlexGrid


is in managing data from database tables in an
unbound state. That is, to populate & edit the FlexGrid
and write the contents back to the database in code.
This may seem a pointless exercise as objects such
Microsoft's Data Bound Grid Control are written
specifically for this purpose, except these grids simply
display the contents of a recordset, record by record,
field by field. Whereas the FlexGid can populate the
grid in any manner, examples of which are:

1. separating grouped data with blank


rows/columns,
2. adding sub/grand-total rows/columns,
3. changing the colour of the cell background or
text in individual or multiple cells,
4. reacting to the state of the data, e.g.
highlighting negative values,
5. validating entered data e.g., numeric values,
positive values, permitted date ranges etc.

142
These are just a few of the possibilities available with
FlexGrids, we'll take a look at more later on.

One important point is that in addition to the grid


controls available as standard to Visual Basic, many
third party grid controls are available that boast
impressive features such as embedded combo boxes,
picture boxes, custom data validation etc. Many of
these are excellent controls, however they all come at
a price proportional to the size of their feature list.

That said, most of the functionality found in these


third party grids can be accessed with FlexGrids with a
little extra code which we'll cover in this article and as
well as saving money, you'll gain knowledge of
creating and customising your grid controls to suit
your specific application and you won't have to
remember to distribute those third part runtime dll's
that custom controls often require.

4.4 Using the FlexGrid

To use the FlexGrid in your application, right click the


Toolbox or select the Project menu and choose
'Components'. The Components dialog box appears as
shown in Figure 1.

143
Figure 5: Components Dialog Box

Select Microsoft FlexGrid Control and copy the


control onto your form from the Toolbox. The default
FlexGrid will appear on the form as shown in Figure
6.

144
Figure 6: Default FlexGrid Appearance

There are a few simple formatting tips to improve to


appearance of the FlexGrid:

First of all, it's good practice to determine the initial


number of grid rows and columns using the Row and
Col properties respectively. Then set the number of
fixed rows and columns (those that hold row and
column headings - raised and in grey) with the
FixedRow and FixedCol properties respectively.

To ensure the columns are the correct width to fit


inside to FlexGrid, first set a variable to the width of
the FlexGrid, allowing for a vertical Scrollbar width.

145
Then use this variable to resize to individual column
widths, by dividing it by the number of columns.

The height of individual rows can be changed to


accommodate multi-line headings. This is done by
simply multiplying the appropriate row height by a
scaling factor, in this case two, to double the height.

When increasing the size of a row height, to make sure


text uses the extra available space, use the WordWrap
property the ensure text continues on the the next cell
line.

Regarding writing text to the grid there are two main


methods. The first one is using the Additem method,
this writes text to an entire row in one action and is
therefore useful for adding headings. The vbTab
constant is used to distinguish adjacent cells. The
second method to populate grid cells with text is to
directly address individual cells and using the
TextMatrix or Text property and set the cell's text.

An example of grid initialisation code would be as


follows:
Dim lngWidth As Long
Dim intLoopCount As Integer
Const SCROLL_BAR_WIDTH = 320

With MSFlexGrid

146
lngWidth = .Width - SCROLL_BAR_WIDTH
.Cols = 4
.FixedCols = 1
.Rows = 0
.AddItem vbTab & "Heading Text One" & vbTab &
_
"Heading Text Two" & vbTab & "Heading Text
Three" & _
vbTab & "Heading Text Four"
.Rows = 12
.FixedRows = 1
.WordWrap = True
.RowHeight(0) = .RowHeight(0) * 2

.ColWidth(0) = lngWidth / 4
.ColWidth(1) = lngWidth / 4
.ColWidth(2) = lngWidth / 4
.ColWidth(3) = lngWidth / 4

For intLoopCount = 1 To (.Rows - 1)


.TextMatrix(intLoopCount, 0) = "Item " &
intLoopCount
Next intLoopCount
End With

The initialised FlexGrid should appear on the form as


shown in Figure 3..

147
Figure 7: Initialised FlexGrid Appearance

Changing Cell Background & Foreground Colours

The ability to change the individual cell background


colour and cell font colour is useful for highlighting
particular data states, e.g. values exceeding a specified
ceiling, negative values, cells where data cannot be
entered etc. To set the background colour of a cell,
first reference the cell by setting the Row and Col
properties to the appropriate cell, then use the
CellBackColor property to set its colour. Similarly use
the CellForeColor property to change the colour of the
text displayed in a cell. Examples of available colours
are found in the FlexGrid's Properties Window under
any of the colour properties, especially the palette tab

148
as this displays a wider range of colours. To set a
range of cells to a selected colour each cell must be
referenced in turn, unless all the cells in the grid are to
have their colour set to the same colour in which case
the BackColor and ForeColor property can be used
which sets the entire grid's colour.

149
UNIT-III
Input –Output Organization: Input –output
interface –I/O Bus and Interface –I/O Bus Versus
Memory Bus –Isolated Versus Memory –Mapped
I/O –Example of I/O Interface. Asynchronous
data transfer: Strobe Control and Handshaking

[Link] & DAO

5.1 ODBC -INTRODUCTION


ODBC (Open Database Connectivity) is an
interface through which data can be accessed in
heterogeneous environments. For example, using
ODBC, data of DB2 can be accessed running on
Mainframe and users can access data of Oracle
running on Sun Sparc and so on. ODBC is an interface
that was promoted by Microsoft Corporation.
5.1.1 Need for ODBC
Let assume that data which is stored in Oracle should
be accessed from a program written in Visual Basic.
For this, set of functions supplied by Oracle called as
APIs (also called as Oracle Call Interface (OCI)) are
used to access Oracle database. In the same way each
database vendor supplies a set of functions using
which database can be accessed. But the problem is,
each set of functions is different from others. That
means if users want to access Oracle using OCI, they
have to learn how to use these functions. But

150
tomorrow if user has to access Sybase, they have to
use functions provided by Sybase to access its
database. That not only makes the life of programmer
tough (as he has to learn a new set of functions again),
it also necessitates great amount of changes to
programs. In brief, each DBMS provides its own set of
functions to access its database. So program becomes
database dependent. That means a change in the type
of database (say from Sybase to Oracle) needs the
program to be modified to a larger extent.
When things were getting more heterogeneous and
database independent programs were much desired,
Microsoft designed a new interface called Open
Database Connectivity (ODBC). Well, in nutshell, it
makes the program database independent. That means
whether accessing of Oracle or Sybase or DB2, user
can write the program and in the same manner they
can shift database from one to another.
5.1.2 How does ODBC Function?
To understand how does ODBC function. Each
database vendor provides a program called as ODBC
driver, which takes standard ODBC calls and
translates them into the language the database can
understand. So the application uses ODBC calls
(called as ODBC API) either directly or indirectly (for
example RDOs calling required ODBC calls) to access
the database. And these ODBC calls are translated by
ODBC driver of the specific database to the required
native language. As a result the program uses the same
ODBC calls irrespective of the database it is accessing

151
and the ODBC driver takes care of converting the
standard calls to the native calls.
But how does system know which ODBC driver to
use? Where are these drivers? Where is the
information regarding these drivers? Who supplies
ODBC drivers? We have to answer to these questions
now.
First of all, each database vendor, such as Oracle
corporation, Microsoft , IBM and so on, provides
ODBC driver for its database. Remember if user do
not have ODBC driver he cannot access the database
using ODBC interface. It should also be noted, that
there are some third party ODBC drivers. There are
companies that are specialized in creating ODBC
drivers, for example Intersolv.
ODBC drivers have to be loaded for database that user
need to access. For example, if user want to access
Oracle, they need to load ODBC driver for Oracle.
When they load ODBC driver, Windows OS stores the
details of the driver in System Registry (a part of
Windows where important information is stored).
ODBC driver manager which is a part of Windows OS
loads the required ODBC driver and passes the calls to
driver and takes results from driver and pass the result
to Application.
ODBC driver manager comes to know about the driver
to be used and the database to be accessed through
using Data source name (DSN) used by the application
program.
5.1.3Data Source Name

152
An ODBC data source is accessed using DSN. Data
source name is a name that identifies the following:
• The name of the database to be used
• The type of the database and the ODBC driver to be
used to access the database
DSN is created using ODBC Data Source
Administrator, which is a program supplied by
Windows OS. It is available in Control panel. When
an application intends to access ODBC data source, it
will create ODBC data source name (DSN) and
accesses database through DSN.
So let us summarize the entire process.
• Application sends ODBC calls to ODBC Driver
Manager
• ODBC Driver Manger sends ODBC calls to the
appropriate ODBC Driver
• ODBC Driver converts ODBC calls to the native
calls and accesses the database.
5.1.4Accessing Oracle Database using ODBC
We have just understood various pieces involved in
accessing an ODBC data source. Now let us access
Oracle database through ODBC. For this purpose we
could use either DAOs or RDOs, but when it comes to
accessing ODBC data source, RDO is the obvious
[Link] are the steps in accessing Oracle:
• Makes sure Oracle is installed in the system and it is
up and running. It can be checked using SQL*Plus. If
it is successfully connected to Oracle using SQL*Plus
that means Oracle is accessible to the user.

153
• Makes sure your system contains ODBC driver for
Oracle. This can be done with ODBC Data Source
Administrator.
• Create a DSN for Oracle database. Use ODBC Data
Source Administrator.
• Use DSN in Visual Basic application to access
Oracle database.
To create DSN to access Oracle:
1. Start ODBC data source administrator by running
ODBC (32 Bit) program from Control Panel of
Windows OS.
2. Select Driver tab and check whether the user has
ODBC driver for Oracle. It may have the name
“Microsoft ODBC for Oracle”. If no ODBC driver for
Oracle is existing, user has to load one before
proceeding.
3. Select User DSN tab and click on Add button.
4. When Create New Data Source dialog is displayed,
select Microsoft ODBC for Oracle (or some other
driver meant for Oracle) and click on Finish button.
5. In Microsoft ODBC for Oracle setup dialog enter
Oracle as Data Source Name, Oracle 7.3 database as
Description.
6. If users are using Personal Oracle, leave remaining
blank. If they are using Oracle Server (Client/Server
Oracle) then enter Oracle service name (the one that
you enter as Host String in Sql*plus) as Server.
7. Click on Ok.
8. User should see a new entry in the list of User Data
Sources.

154
5.2 DATA ACCESS OPTIONS
5.2.1. INTRODUCTION
Visual Basic provides variety of options when it
comes to accessing the data stored in the database.
Find all options below.

(i) Data Access Objects (DAO) - It communicates with


the Microsoft access and other ODBC compliant data
sources through the JET engine.

(ii) ODBC Direct - It allows accessing ODBC data


sources through the RDO (Remote Data Objects) and
DAO objects bypassing the JET database engine.

(iii) Data Control - It binds data-aware controls to


Microsoft access or other ODBC data sources.

(iv) Remote Data Objects (RDO) - It provides a frame


work for using code to create and manipulate
components of a remote ODBC database system.

(v) Remote Database Control - It binds to controls to


an ODBC remote database.

5.2.2 Data Access Objects

When Visual Basic first started working with


databases, it used the Microsoft Jet database engine,
which is what Microsoft Access uses. Using the Jet
engine represented a considerable advance for Visual

155
Basic, because now you could work with all kinds of
data formats in the fields of a database: text,
numbers, integers, longs, singles, doubles, dates,
binary values, OLE objects, currency values,
Boolean values, and even memo objects (up to
1.2GB of text). The Jet engine also supports SQL,
which database programmers found attractive.

Fig F.5.1
The figure F.5.1 shows the Data Access objects
Hierarchy.

156
To support the Jet database engine, Microsoft added
the data control to Visual Basic, and you can use
that control to open Jet database (.mdb) files.
Microsoft also added a set of Data Access Objects
(DAO) to Visual Basic:
• DBEngine—The Jet database engine
• Workspace—An area can hold one or
more databases
• Database—A collection of tables
• TableDef—The definition of a table
• QueryDef—The definition of a query
• Recordset—The set of records that make
up the result of a query
• Field—A column in a table
• Index—An ordered list of records
• Relation—Stored information about the
specific relationship between tables

5.2.3The Data Control

The data control enables you to move around


in a database from record to record and to display
and manipulate data from the records in bound
controls. This control displays a set of arrow buttons
the user can manipulate to move through a database
and the records from that database are displayed in

157
bound controls. In fact, you can perform most data
access operations using the data control—without
writing any code. Data-bound controls automatically
display data from one or more fields for the current
record, and the data control performs all operations
on the current record. If the data control is made to
move to a different record, all bound controls
automatically pass any changes to the data control to
be saved in the database. The data control then
moves to the requested record and passes back data
from the current record to the bound controls where
it’s displayed.
When an application begins, Visual Basic uses data
control properties to open a selected database,
create a DAO Database object, and create a
Recordset object. The data control’s Database and
Recordset properties refer to those Database and
Recordset objects, and you can manipulate the data
using those properties. For example, if you have an
SQL statement to execute, you place that statement
in the data control’s RecordSource property, and
the result appears in the Recordset property.
5.2.4 Steps for creating an ODBC Data Source
Name
1. In the Windows Control Panel, double-
click Administrative Tools. The
Administrative tools window opens.

158
2. Double-click Data Sources (ODBC). The
ODBC Data Source Administrator window
opens.
3. Select the System DSN tab and click Add.
The Create New Data Source dialog opens.
4. Select an appropriate Oracle driver and
click Finish. The Oracle ODBC Driver
Configuration window opens.

5. Specify the following information in the Oracle


ODBC Driver Configuration window:
• In the Data Source Name field, enter a name
of your choice to identify the data source. If
your DBA has supplied a common DSN for use
across the enterprise, enter it here.

159
• In the Description field, enter an optional
description for the data source.
• In the TNS Service Name drop-down, select
the TNS Service Name for the database your
workspace repositories will be stored in. If no
choices are shown, or if you are unsure which
name to select, contact your DBA.
• In the User ID field, enter the database user ID
supplied by your DBA.
6. Click Test Connection. The Oracle ODBC Driver
Connect window opens.
7. In the Oracle ODBC Driver Connect window
the Service Name and User ID fields are prefilled
with the information you supplied in the Oracle
ODBC Driver Configuration window. Enter the
password for your user ID and click OK. You are
notified that the connection was created
successfully. Click OK.
8. Click OK to exit the Driver Configuration
window. Then click OK again to exit the ODBC
Data Source Administrator window.
5.2.5 Operations with DAO RecordSet

How to: Add a Record to a DAO Recordset


You can add a new record to a table-type or dynaset-
type Recordset object by using the AddNew method.
To add a record to a table-type or dynaset-
type Recordset object:

160
1. Use the AddNew method to create a record
you can edit.
2. Assign values to each of the record's fields.
3. Use the Update method to save the new
record.
Dim dbsNorthwind As [Link]
Dim rstShippers As [Link]
Set dbsNorthwind = CurrentDbSet rstShippers =
[Link]("Shippers")
[Link]
rstShippers!CompanyName = "Global Parcel Service"
.
. ' Set remaining fields.
[Link]
When you use the AddNew method, the Microsoft
Access database engine prepares a new, blank record
and makes it the current record. When you use
the Update method to save the new record, the record
that was current before you used the AddNew method
becomes the current record again.
The new record's position in the Recordset depends
on whether you added the record to a dynaset-type or a
table-type Recordset object. If you add a record to a
dynaset-type Recordset, the new record appears at the
end of the Recordset, no matter how the Recordset is
sorted. To force the new record to appear in its
properly sorted position, you can either use
the Requery method or recreate the Recordset object.
If you add a record to a table-type Recordset, the
record appears positioned according to the current

161
index, or at the end of the table if there is no current
index. Because the Access databse engine allows
multiple users to create records in a table
simultaneously, your record may not appear at the end
of the Recordset. Be sure to use
the LastModified property rather than
the MoveLast method to move to the record you just
added.

How to: Count the Number of Records in a DAO


Recordset
You may want to know the number of records in
a Recordset object. For example, you may want to
create a form that shows how many records are in each
of the tables in a database. Or you may want to change
the appearance of a form or report based on the
number of records it includes.
The RecordCount property contains the number of
records in a table-type Recordset or the total number
of records accessed in a dynaset- or snapshot-
type Recordset. A Recordset object with no records
has a RecordCount property value of 0.

When you open a table-type Recordset object, you


effectively visit all of the records in the underlying
table, and the value of the RecordCountproperty
equals the number of records in the table as soon as
the Recordset is opened. Canceled transactions may
make the value of the RecordCountproperty out-of-
date in some multiuser situations. Compacting the

162
database restores the table's record count to the correct
[Link] following example creates a snapshot-
type Recordset object, and then determines the
number of records in the Recordset:
Function FindRecordCount(strSQL As String) As
Long
Dim dbsNorthwind As [Link]
Dim rstRecords As [Link]
On Error GoTo ErrorHandler
Set dbsNorthwind = CurrentDb
Set rstRecords =
[Link](strSQL)
If [Link] Then
FindRecordCount = 0
Else
[Link]
FindRecordCount = [Link]
End If
[Link]
[Link]
Set rstRecords = Nothing
Set dbsNorthwind = Nothing
Exit Function
ErrorHandler:
MsgBox "Error #: " & [Link] & vbCrLf &
vbCrLf & [Link]
End Function
As your application deletes records in a
dynaset-type Recordset, the value of
the RecordCount property decreases. However, in a

163
multiuser environment, records deleted by other users
are not reflected in the value of
the RecordCount property until the current record is
positioned on a deleted record.
At that time, the setting of
the RecordCount property decreases by one. Using
the Requery method on a Recordset,followed by
the MoveLast method,sets the RecordCount property
to the current total number of records in
the Recordset. A snapshot-type Recordset object is
static and the value of its RecordCount property does
not change when you add or delete records in the
snapshot's underlying table.

How to: Create a DAO Recordset from a Form


You can create a Recordset object based on an Access
form. To do so, use the RecordsetClone property of
the form. This creates a dynaset-type Recordset that
refers to the same underlying query or data as the
form. If a form is based on a query, referring to
the RecordsetClone property is the equivalent of
creating a dynaset with the same query. You can use
the RecordsetClone property when you want to apply
a method that cannot be used with forms, such as
the FindFirst method. The RecordsetClone property
provides access to all the methods and properties that
you can use with a dynaset.

The following example shows how to assign


a Recordset object to the records in the Orders form:

164
Dim rstOrders As [Link]
Set rstOrders =
Forms![Link]
This code always creates the type of Recordset being
cloned (the type of Recordset on which the form is
based); no other types are available. Note that
the Recordset object is declared with the object
library qualification. Because Access can use both
DAO and ADO, it is better to fully qualify the data
access variables by including the object library
reference name.

How to: Create a DAO Recordset From a Query


You can create a Recordset object based on a stored
select query. In the following example, Current
Product List is an existing select query stored in the
current database:
Dim dbsNorthwind As [Link]
Dim rstProducts As [Link]
Set dbsNorthwind = CurrentDb
Set rstProducts=
.OpenRecordset("Current Product
List")
If a stored select query does not already exist,
the OpenRecordset method also accepts an SQL
string instead of the name of a query. The previous
example can be rewritten as follows:
Dim dbsNorthwind As [Link]
Dim rstProducts As [Link]
Dim strSQL As String

165
Set dbsNorthwind = CurrentDb
strSQL = "SELECT * FROM Products WHERE
Discontinued = No " & _"ORDER BY ProductName"
Set rstProducts
=[Link](strSQL)
The disadvantage of this approach is that the query
string must be compiled each time it runs, whereas the
stored query is compiled the first time it is saved,
which usually results in slightly better performance.
How to: Create a DAO Recordset from a Table in
the Current Database
The following example uses
the OpenRecordset method to create a table-
type Recordset object for a table in the current
database:
Dim dbsNorthwind As [Link]
Dim rstCustomers As [Link]
Set dbsNorthwind = CurrentDb
Set rstCustomers =
[Link]("Customer
s")

How to: Create a User-Defined Property


This example tries to set the value of a user-defined
property. If the property does not exist, it uses
the CreateProperty method to create and set the value
of the new property.
Sub CreatePropertyX()
Dim dbsNorthwind As Database
Dim prpLoop As Property

166
Set dbsNorthwind = OpenDatabase("[Link]")
' Set the Archive property to True.
SetProperty dbsNorthwind, "Archive", True
With dbsNorthwind
[Link] "Properties of " & .Name
' Enumerate Properties collection of the
Northwind database.
For Each prpLoop In .Properties
If prpLoop <> "" Then [Link] " " & _
[Link] & " = " & prpLoop
Next prpLoop
' Delete the new property because this is a
' demonstration.
.[Link] "Archive"
.Close
End With
End Sub

Sub SetProperty(dbsTemp As Database, strName As


String, _booTemp As Boolean)
Dim prpNew As Property
Dim errLoop As Error
' Attempt to set the specified property.
On Error GoTo Err_Property
[Link]("strName") = booTemp
On Error GoTo 0
Exit Sub
Err_Property:
' Error 3270 means that the property was not found.
If [Link](0).Number = 3270 Then

167
' Create property, set its value, and append it to the
' Properties collection.
Set prpNew = [Link](strName, _
dbBoolean, booTemp)
[Link] prpNew
Resume Next
Else
' If different error has occurred, display message.
For Each errLoop In [Link]
MsgBox "Error number: " & [Link] &
vbCr & _errLoop.Description
Next errLoop
End
End If
End Sub

How to: Delete a Record From a DAO Recordset

You can delete an existing record in a table or dynaset-


type Recordset object by using the Delete method.
You cannot delete records from a snapshot-
type Recordset object. The following example deletes
all the duplicate records in the Shippers table:
Sub DeleteDuplicateShippers()
Dim dbsNorthwind As [Link]
Dim rstShippers As [Link]
Dim strSQL As String
Dim strName As String
On Error GoTo ErrorHandler
Set dbsNorthwind = CurrentDb

168
strSQL = "SELECT * FROM Shippers ORDER BY
CompanyName, ShipperID"
SetrstShippers=[Link]
(strSQL,dbOpenDynaset)
'If no records in Shippers table, exit.
If [Link] Then Exit Sub
strName = rstShippers![CompanyName]
[Link]
Do Until [Link]
If rstShippers![CompanyName] = strName Then
[Link]
Else
strName = rstShippers![CompanyName]
End If
[Link]
Loop
Exit Sub
ErrorHandler:
MsgBox "Error #: " & [Link] & vbCrLf &
vbCrLf & [Link]
End Function
When you use the Delete method, the Microsoft
Access database engine immediately deletes the
current record without any warning or prompting.
Deleting a record does not automatically cause the
next record to become the current record; to move to
the next record you must use the MoveNext method.
However, keep in mind that after you have moved off
the deleted record, you cannot move back to it.

169
If you try to access a record after deleting it on a table-
type Recordset, you will see error 3167, "Record is
deleted." On a dynaset, you will see error 3021, "No
current record."
If you have a Recordset clone positioned at the
deleted record and you try to read its value, you will
see error 3167 regardless of the type
of Recordsetobject. Trying to use a bookmark to
move to a deleted record will also result in error 3167.

170
[Link] EXE and ActiveX DLL

6.1 INTRODUCTION
A standard exe application is one that is created using
Standard EXE project. It is the most widely used
Project type using VB6. Standard EXE application is
normally the most widely used among the available
Project types in Visual Basic. Stand-alone programs
have an .EXE file extension.
A standard EXE application is normally used when
you want to develop a stand-alone application.
Examples include calculators, text editors, and other
similar applications. An ActiveX EXE application is
one that is created using ActiveX EXE project.
ActiveX EXE are widely used in conjunction with
standard EXE applications. There are three types of
widely used of ActiveX projects. These are:
a. ActiveX EXE
b. ActiveX DLL
c. ActiveX Control

ActiveX EXE: Unlike a stand-alone EXE file, an


ActiveX EXE file is designed to work as an OLE
server, which is nothing more than a program designed
to share information with another program. It has an
.EXE file extension.
ActiveX DLL: ActiveX DLL files are not meant to be
used by themselves. Instead, these types of files
contain subprograms designed to function as building
blocks when creating a stand-alone program. It has a

171
.DLL file extension.
ActiveX Control: Unlike an ActiveX DLL or
ActiveX EXE file, an ActiveX Control file usually
provides both subprograms and a user interface that
you can reuse in other programs. It has an .OCX file
extension.

6.2 ActiveX EXE/DLL Usages

1. The ActiveX EXE/DLL is normally used when


you need to build a component that is separate
from the main program. The concept is based on
COM model.
2. ActiveX DLL/EXE allows multiple applications
to share the same code. This allows for
scalability of programs, and saves time because
you only need to write the code once.
3. ActiveX DLLs and ActiveX EXEs are almost
same in the ways they are built and used. In
either case, you build one or more classes that
applications can use to do something.
4. One of the main differences between ActiveX
EXE and an ActiveX DLL's is that the code is
executed within the main program's address
space for ActiveX DLL. This is because the code
lies inside the program's address space, calling
methods and execution of code is very fast.

6.3 Comparing Standard EXE ActiveX EXE/DLL


projects

172
An ActiveX Exe provides the reusability of code, by
accessing it from different clients.
An ActiveX Exe is a component that can be called by
another application by providing a reference to the
component. But a Standard Exe application cannot be
called in this way.
An ActiveX EXE's code is run in a separate process.
When the main program calls an ActiveX EXE's
method, the application passes required parameters
into the ActiveX EXE's and calls the method. The
ActiveX EXE, upon execution may return the results
to the main program. This is slower than running an
ActiveX DLL's method inside the main program's
address space.

6.4 Developing a Standard EXE file, with an


example
Now, we develop our Standard EXE application that
uses the ActiveX component developed earlier.
1. Open Visual Basic 6.0 - it should be on your start
menu if you have just installed it (Programs ->
Microsoft Visual Basic 6.0 -> Microsoft Visual Basic
6.0)
Open another instance of Visual basic, select the
“Standard EXE” and click “Open”.

173
Fig: F.6.4.1 ActiveX-6; Dialog Box showing the type
of project to open.
Change the name property of form to frmTestActivex
and caption to “Test form”.
Object Property Setting
CmdShowSelVal
Command Name
Show Selected Value in ActiveX
button Caption
Exe
Command Name cmdCallActivex
button Caption Show Form From ActiveX Exe
optNumbers
Option Name
Choose Numbers in
button Caption
ActiveX Exe

174
OptAlphabets
Option Name
Choose Alphabets in ActiveX
button Caption
Exe

Select References from Project menu by going to


“Project- > References”.
On selecting References Menu item a dialog box as
shown below will be opened.
Select the ActiveX Exe made in the above project and
click on OK. In case you don’t see the ActiveX
component that you had just made, use “Browse”
button locate and select the component.
Following code should be included in Form.

'variable of type clsActivexEx class in Activex_ex


component
Dim actvixTest As clsActivexEx
Option Explicit
Private Sub cmdCallActivex_Click()
'create an object for class clsActivexEx in AxtivexEx
component
Set actvixTest = New clsActivexEx
'call the LoadForm method
'and pass the values of both te option buttons
'which tells the option that the user has choosen
'and what drop-down box to enable
[Link] [Link],
[Link]
End Sub

175
Private Sub CmdShowSelVal_Click()
'function that gets the value selected in ActiveX Exe
'and dispalys in a message box
If actvixTest Is Nothing Then
MsgBox "You have selected Nothing.", 64,
"Selected Item in ActiveX Exe"
Else
MsgBox "You have selected " &
[Link] & " in ActiveX Exe.", ,
"Selected Item in ActiveX Exe"
End If
End Sub

Fig: F.6.4.3. ActiveX-8; References Dialog Box

176
6.5 Interacting with ActiveX exe from Standard
exe and vice versa.
To demonstrate how the Standard EXE interacts with
the ActiveX EXE, run the test project. Assuming that
the code is entered properly, a form as shown below is
displayed:

Fig : F.6.5.1 ActiveX-9; Test Form


Select either of the options on the form and click on
“show form from ActiveX Exe” Button.

Fig : F.6.5.2 ActiveX-10; Test Form Selection

177
On selecting and clicking the button opens a form in
ActivexEx Component as shown in below figure.
In this case, Alphabets Drop-Down box is disabled as
“Choose Numbers in ActiveX Exe” has been selected.
Here a value is passed from Standard Exe to ActiveX
Exe based on the option button we selected and its
corresponding drop-down box is enabled in ActiveX.

Fig : F.6.5.3 ActiveX-11; ActiveX EXE call.

Select any number from the drop-down box (Numbers


Drop-down box in this case) and click on “Select and
close” Button.

178
Fig : F.6.5.4 ActiveX-12; Here the Control is passed to
the ActiveX EXE application.

On clicking the “Select and close” button the form in


ActiveX Exe is closed, and the control is passed back
to the Main (Standard EXE file). However, note that
the ActiveX EXE is still running in the background. It
is possible to close ActiveX EXE, if so desired. In our
example, it would be closed only when the Main
application is closed.
Now click on “Show Selected Value in ActiveX Exe”
button to see the item that is selected in ActiveX Exe.
Here the number/alphabet selected in ActiveX passed
to Standard Exe.

179
Fig : F.6.5.5 ActiveX-13; Control is passed back to the
Main (Standard EXE).
Below shows the item that was selected in ActiveX
Exe.

Fig: F.6.5.6 ActiveX-14; The selected number is


displayed in the Main (Standard EXE).

180
As you can see, in the above example, we have
selected “numbers” in the Standard EXE, and later
selected “2” in the ActiveX EXE. The number “2” is
passed on to the Standard EXE upon request.
Note that this is only a brief example provided to
demonstrate the concept. Practically, the ActiveX
EXE/DLL could be quite large, such as a calculator.
The calling program may be a Text Editor.

Class Module:
Option Explicit
Public Function LoadForm(numbers_disp As Boolean,
alphabets_disp As Boolean) 'Load the form
Load frmActivexEx
[Link] = [Link]
'make the controls on the form as disabled initially
[Link] = False
[Link] = False
'Based on the option user selected
'make its corresponding drop-down box enabled
If numbers_disp = True Then
[Link] = True
ElseIf alphabets_disp = True Then
[Link] = True
End If
[Link]
End Function
Private Sub Class_Initialize()

181
'selectedItem is a global variable declared in
module
'set it to nothing initially
'whcih implies that no item has been selected
selectedItem = "Nothing"
End Sub
Private Sub Class_Terminate()
'on terminating unload the form
Unload frmActivexEx
End Sub
Public Function getselectedchar() As String
'function that gets the item selected in the
drop-down box
getselectedchar = selectedItem
End Function
Form ActiveX :
Option Explicit
Private Sub cboAlphabets_Click()
'assign the selectedItem variable to the item
that is selected in the drop-down box
selectedItem = [Link]
'variable of type clsActivexEx class in Activex_ex
component
Dim actvixTest As clsActivexEx End Sub
Private Sub cboNumbers_Click()
'assign the selectedItem variable to the item that
is selected in the drop-down box
selectedItem = [Link]
End Sub
Private Sub cmdSelAndClose_Click()

182
Unload Me
End Sub
Standard Module :
Option Explicit
'global variable which stores the item selected
in drop-down box
Public selectedItem As String

Standard EXE Form code:


Option Explicit
Private Sub cmdCallActivex_Click()
'create an object for class clsActivexEx in
AxtivexEx component
Set actvixTest = New clsActivexEx
'call the LoadForm method and pass the
values of both the option buttons 'which tells
the option that the user has chosen and what
drop-down box to 'enable
[Link] [Link],
[Link]
End Sub
Private Sub CmdShowSelVal_Click()
'Function that gets the value selected in
ActiveX Exe and displays in a 'message box
If actvixTest Is Nothing Then
MsgBox "You have selected Nothing.", 64,
"Selected Item in ActiveX Exe"
Else
MsgBox "You have selected " &
[Link] & " in ActiveX

183
Exe.", , "Selected Item in ActiveX Exe"
End If
End Sub
Private Sub Form_Unload(Cancel As Integer)
Set actvixTest = Nothing
End Sub
6.6 ACTIVEX DLL
Why?
You make an ActiveX DLL or EXE to allow multiple
applications to share the same code. This saves you time
because you only need to write the code once. It also lets
you devote extra time to debugging the shared code. If
you are going to use the code in a lot of different
applications, you can perform extra tests to make sure
the code works correctly and still save time
[Link] the code also lets you fix, upgrade,
and otherwise modify the shared library relatively easily.
You can update the shared DLL/EXE and all of the
applications that use it are automatically updated. The
Binding section talks more about this.
Which?
ActiveX DLLs and ActiveX EXEs are almost exactly the
same in the ways they are built and used. In both cases,
you build one or more classes that applications can use to
do something. The big difference lies in where they are
used. An ActiveX DLL's code is executed within the
main program's address space. It behaves as if the class
was created within the main program's code. Because the
code lies inside the program's address space, calling
methods is very fast.

184
An ActiveX EXE's code is run in a separate process.
When the main program calls an ActiveX EXE's method,
the system marshalls the call to translate the parameters
into the ActiveX EXE's address space, calls the method,
translates the results back into the main program's
address space, and returns the result. This is slower than
running an ActiveX DLL's method inside the main
program's address [Link] of the difference in
speed, an ActiveX DLL is almost always preferable. The
reason ActiveX EXEs are useful is they can run on a
different computer than the main program while an
ActiveX DLL must run on the same computer as the
main [Link] you want to build a library of shared
routines to save programming and debugging, use an
ActiveX DLL because it will give you better
performance. Even if you need to distribute several
copies of the DLL on different computers, it will
probably be worthwhile.
If you want a centralized server library, use an ActiveX
EXE. The EXE can sit on a central computer and work
directly with that computer's resources. If you need to
frequently change how the code works, you can easily
change it in one place.
6.6.1 Making an ActiveX DLL/EXE Project
Start a new project and select ActiveX EXE or ActiveX
DLL. Initially the project is named Project1 and contains
a class named Class1. Change these to meaningful
names. The model Microsoft has in mind is a DLL/EXE
contains several related classes that each perform related
functions. For example, a DLL might contain billing

185
system classes named Customer, Product, and
SalesPerson. The Customer class would contain methods
for manipulating customer data. In this example, you
might change the project name to BillingObjects. You
would change Class1's name to Customer and add two
more classes named Product and SalesPerson. Give the
class Public functions and methods to perform whatever
tasks it should. The main program can only invoke the
Public class methods.
Instancing :
Set the classes' Instancing properties to determine how
the object can be created. In VB6 the allowed values are:
• Private : Code outside the DLL/EXE cannot
create this object type. Other classes in the
DLL/EXE can use this type of class as a helper
but the main program cannot use it.
• PublicNotCreatable : The main program can use
this type of class but cannot create new
instances using the New keyword or with
CreateObject. In this case, you need to provide
some method within the other classes to create
the new object and return it to the main
program.
• SingleUse : The main program can create the
object. Every time you create a new object, the
system makes a new ActiveX EXE instance to
service the object you created. Among other
things, if the EXE contains global variables then
different objects you create get different copies

186
of the variables. This option is allowed for
ActiveX EXEs only.
• GlobalSingleUse:Similar to SingleUse except
you can invoke the properties and methods of
the class as if they were simple global
functions. This option is allowed for ActiveX
EXEs only. See GlobalMultiUse later for more
details.
• MultiUse:The main program can create the
object. When it does, the system makes an
ActiveX DLL/EXE component to handle the
object. If you make other objects, the system
uses the same ActiveX DLL/EXE component to
handle them. This can be a little confusing
depending on whether you are building a DLL
or EXE and whether an EXE is running on
different computers.
If you build an ActiveX DLL, all programs run the
DLL code in their own address spaces. That means
different objects created in the same program will
share the same component server so they could
share global variables defined in the DLL. However,
if the objects are all freed at the same time, the
component server will shut down so any global
values will be lost.
The code in the SharedDll directory available for
download demonstrates this kind of sharing. The
BillingObjects,vbp project contains the project named
BillingObjects. This project holds a BAS module holding
a public variable named g_TheNumber. This variable is

187
visible to other code in the project but not to a main
program using the DLL.
The BillingObjects project also contains a MultiUse
class named Customer. This class has Property Let and
Property Get procedures that set and get the value of
g_TheNumber.
The main program uses two Customer objects like this:
Private m_Customer1 As Object
Private m_Customer2 As Object
Private Sub Form_Load()
Set m_Customer1 =
CreateObject("[Link]")
Set m_Customer2 =
_CreateObject("[Link]")
End Sub
Private Sub cmdGet_Click()
[Link] = m_Customer1.TheNumber
End Sub
Private Sub cmdSet_Click()
m_Customer1.TheNumber =
CInt([Link])
[Link] = ""
End Sub
In the DLL project, open the File menu and select Make
[Link] to build the DLL. Notice how the main
program uses the CreateObject function to create its
instances of the Customer class. The name of the class is
the project's name followed by the class name:
[Link].

188
Notice also that the program creates the two Customer
objects when it starts and it keeps those objects running.
That means the component stays running so the objects
share the value of g_TheNumber. If you use the Set
button to save a value into this variable and then use the
Get button to retrieve the value, you should get back the
value you saved.
This behavior is what you would expect if you included
the DLL's modules directly inside the main program. If
you want that behavior, make the DLL MultiUse. If you
want each class object to have its own global variables,
make the DLL SingleUse. Or better still, move the
variables inside the class so each object gets its own
variables but you still only need one component instance.
That will save some overhead.
The interesting thing is any program that uses a shared
component server can share the values. Compile the test
program and use Windows Explorer to launch two
instances of the program. Enter 1234 in one instance and
click Set. Then click Get in the other instance. The
second program should see the value set by the first.
Note that this sometimes gets messed up and a
component server is left running so you may end up with
two programs running different component servers. The
ActiveX EXE project in the SharedExe directory
demonstrates this sharing using an ActiveX EXE. It's
basically the same as the previous example except is uses
an ActiveX EXE instead of a DLL. Compile the test
program and use Windows Explorer to launch two
instances of the program. Enter 1234 in one instance and

189
click Set. Then click Get in the other instance. The
second program should see the value set by the first.
• GlobalMultiUse: This is similar to MultiUser
except the main program can reference methods
and properties as if they were globally declared.
The code in the GlobalMultiUse directory
demonstrates this. The ActiveX EXE code is the
same as in the previous example except the
Customer class is marked GlobalMultiUse. The
main program uses the Customer's TheNumber
property procedures like this:
Private Sub cmdGet_Click()
' Implicit [Link]
[Link] = TheNumber
End Sub
Private Sub cmdSet_Click()
TheNumber = CInt([Link])
[Link] = ""
End Sub

This code simply uses the TheNumber procedures as if


they were globally declared. When the program invokes
one of the methods using this global syntax, it creates an
instance of the class to use its methods. It continues to
use that instance whenever it needs to execute a global
[Link] you explicitly create other instances of the
class, you get new object not the global one.

This all seems pretty confusing so avoid using


GlobalMultiUse and GlobalSingleUse. They let you use

190
a syntax that is more similar to that used by DLLs built
in C++ and other languages and that's probably why
Microsoft implemented these. They hide the fact that
there is an underlying class object, however, so they
increase your chances for confusion.
Test Projects
The previous sections glossed over a few details dealing
with test projects. After you create your ActiveX DLL
project, you can add a test application. Open the File
menu, select Add Project, and add a Standard EXE. That
project can act as the main program to test your DLL.
This is handy because it means you don't need to
compile the DLL before you can test it. It also means
you don't need to jump back and forth between the DLL
and test application projects.
After you have the DLL code working, you can compile
it into a DLL file. Then you can create independent
applications to use it.
6.6.2 Binding
You can bind your DLL or EXE either at runtime (late
binding) or at design time (early binding). When you use
early binding, you tell the main program all about the
DLL. That lets it do things like provide intellisense for
the DLL's methods. It is also faster than late binding.
Early Binding
To use early binding, load the main program, open the
Project menu, and select References. Find your DLL in
the list and select it. If the DLL project's name is
BillingObjects, then look for an entry named
BillingObjects. If you have had a couple versions of the

191
project in different locations, you may see more than one
entry. Click on one and look at the location displayed
near the bottom of the dialog to see if you have the right
one. If you can't figure it out, click the Browse button
and find the DLL yourself. When you have selected the
DLL, click OK.
Now the program can explicitly refer to the classes in the
DLL. For example, it could declare and create a
Customer object like this:
Dim customer1 As Customer
Set customer1 = New Customer
If you now type "customer1.", intellisense will be able to
list the public methods provided by the Customer class.
In this example, this is just the TheNumber property
procedure.
Early binding has the disadvantage that it imposes more
restrictions on the DLL's compatibility. If you change the
DLL's methods as they are visible to outside code, the
main program will no longer have a correct picture of the
DLL. For example, if you add a new Public method to a
class, the main program will not know about that
method. When you try to create an instance of the class,
the system will decide that the program is looking for an
incompatible DLL version and will display the message:
Class does not support Automation or does not support
expected interface
To fix this, load the main program, open the Project
menu, and select References. Deselect the DLL and click
OK. Then open the References dialog again and reselect
the DLL. Now the program will work again.

192
Depending on your exact arrangement, you may also get
the error:
Type mismatch
To fix this, recompile the main program.
Late Binding
To use late binding, declare references to DLL objects to
have type Object. Then use the CreateObject statement
to instantiate the objects like this:
Dim customer1 As Object
Set customer1
=CreateObject("[Link]")
This code creates an instance of the Customers class that
is defined by the DLL project named BillingObjects.
After this the program can use the Public properties and
methods of the customer1 object just as if it had declared
it using early binding.
Now if you change the DLL's public methods, the
compiled executable will still work (if you removed the
methods the program uses). The downside with late
binding is you don't get intellisense and calling the
DLL's methods takes longer than it does with early
binding.

193
UNIT IV
Priority Interrupt: Daisy-Chaining Priority,
Parallel Priority Interrupt. Direct Memory
Access: DMA Controller, DMA Transfer. Input –
Output Processor: CPU-IOP Communication.

[Link] LINKING AND EMBEDDING


(OLE)

7.1 INTRODUCTION-WHAT IS OLE?


OLE definition is that, OLE (pronounced as
oh-leh) was originally mean as 'object linking and
embedding', it is a Microsoft compound document
technology based on Component Object
Model (COM), and it is introduced into Microsoft
Windows 3.1. 'OLE (object linking and embedding)'
gives all Windows applications a standard way to
create compound documents that create objects within
one Microsoft application and embed them into other
document. OLE object meaning is graphic,
spreadsheet, MSWord, etc. that can be embedded into
a document called the "container application." If the
object allowed to be edited, the application associated
with it is called "server application".
7.2 OLE - Objects and Classes:
Each object in VB is defined by a class. A class
describes the variables, properties, procedures, and
events of objects. Objects are instance of classes; we

194
can create as many objects for the class which have
defined.
Ways of creating an object in VB:
1. The Custom Control command on the
tools menu is used for adding object in
the toolbox and it it drawn directly on the
form.
2. The functions CreateObject or GetObject
are used to create on object.
3. The object can be embedded or linked
within an OLE container control.
As an example we can say the form we work with
during design time is a class and during the run time
VB creates in instance of a class.
OLE Server: This is an application that can provide
objects to other applications. This is also called as
OLE Source application.
OLE Client :
This is an application that uses objects provided by
OLE Server. This is also called as OLE Container as it
contains objects provided by OLE Server. Not every
application is an OLE Server. Only a few applications
are capable of providing objects. In the same way not
all applications are capable of receiving objects.
However, there are applications, such as MS-Word
and MS-Excel that are capable of being OLE source as
well as OLE Container.
7.3Object Embedding
In object embedding, an object is embedded in the
client application. Along with the object, client

195
application also stores the information regarding
source application (or server) that created the object.
The data stored in client application is separate and no
link is maintained between the data supplied by source
application and data stored in client application.
The advantage with Object Embedding is, client
application maintains its own copy of the data. The
disadvantage is, changes made to original data (in
source application) will not be incorporated in the data
maintained by client.
Whenever you double click on the object in container
application, the source application will be invoked (as
information regarding source application is
maintained) and the data of client application is placed
in source application for editing.
The following example, where we embed a few cells
of Excel spreadsheet to a Word document, will make
this process clear:
1. A collection of cells from a spreadsheet of MS-
Excel is copied to clipboard. As MS-Excel is an OLE
Server, it copies the data in the form of an object.
2. Paste the data (now in the form of an object) from
Clipboard to a document in Ms-Word.
3. Now the data is embedded into MS-World
document as an object. Ms-Word document contains
its own copy of the data.
4. If you double click on the object in MS-Word, then
an instance of MS-Excel is invoked and data from
MS-Word is copied into MS-Excel.
5. User can edit embedded data using MS-Excel.

196
6. If user saves changes and exits MS-Excel then
modified data is placed in MS-Word document.
As you have seen in the above example, once an
object is embedded into MS-Word, you do not have to
invoke source application manually, instead just
double click on the object and that will invoke source
application automatically.
However, if data is changed in the original worksheet
of MS-Excel then those changes are not copied to the
data in MS-Word. This is because in Object
Embedding, source and container applications
maintain two different copies of the data.

7.4 Object Linking


Object linking makes changes made to source
application available to container application. This is
because container doesn’t store a separate copy of the
data, instead it maintains a link to data in a source
application.

7.5 The Advantages & Disadvantages of Object


Linking & Embedding
Object linking and embedding (OLE) refers to the
practice of providing a link in a document directly to a
source of data or a graphic or embedding that data or
graphic in the document itself. OLE's features make it
a convenient tool for those creating documents or
presentations that need to be kept up to date, but it
have some downsides as well.

197
[Link] Information
You can maintain control over the source through
object linking. The link goes back to information that
you can control, so you can quickly and conveniently
update the information or graphic without needing to
point the user to a new source. A person can go back
and revisit the link over and over again to get the new
information.
2. Convenience
An embedded file can be quite convenient for users of
the presentation or document, as they will be able to
view the file or graphic right in the document without
having to click through a link or follow a web address,
which may require the user to log in first or jump
through other hurdles.

3. Restricted Access
All users have to have access to the file and the
application that runs it, which may prove to be a
disadvantage if you have people who need to access
the link who don't have the right permissions or who
aren't able to install the correct program. In that case,
your presentation or document is only as good as the
privileges or software that your users have. This is not
as big of a problem if you have a lot of users who are
on the same network or work in the same office.

4. Embed Problems
An embedded file will show up as just a snapshot or it
won't be displayed at all if a user can't obtain access to

198
the file. This can derail a critical presentation or
document that depends on the information you are
embedding within it. You may have to test the embed
from the systems that will need to reach it to ensure
that it works, which may take a lot of time to do.

SOME OLE Terminology:

• Compound document - document


containing elements from multiple
applications
• Embedded object - original object is copied
and stored in the compound document
• Linked object - original object remains
stored in original file and is linked to
container document
• Container document - the compound
document that contains elements from
multiple applications

7.6 OLE CONTAINER CONTROL

This allows adding objects from other applications. An


OLE control can have only one object at a time.

7.6.1 Creation of objects at Design Time

199
Each time an OLE control is drawn on a form, an
Insert Object dialog box appears as shown in
following Fig. F.7.3

Fig F.7.3
Example :
This example is used to create a link from an existing
application.
• When an OLE control to a form, the Insert
Object dialog box appears in order to allow
you to insert an OLE object into the new
control. New OLE object is created with the
Insert Objectdialog box. However, it can also
embed or link to an existing file.

200
• Click the Create From File option button in
the Insert Object dialog box. When a file is
selected by typing its path and name into the
File text box or by using the Browse button,
and then click on OK, that file is embedded
as an OLE object in the OLE control.
• Embedding an existing file by this way is
handy and it saves the time of creating the
file over again from scratch in a new OLE
object.
7.6.2 Creating an Embedded object at Design Time
The following example will create a new file using
OLE container.
• OLE control is drawn in the [Link]
dialog box is displayed.
• ‘Create new’ option is chosen and MSExcel
worksheet is selected from the list of options
as in the figure F.7.3
• Right click on the OLE container and choose
Open.
• Then excel sheet is opened and details can be
added and it is saved as ‘[Link]’ as in the
fig F.7.4

201
Fig F.7.4

Fig F.7.5
7.6.3 Creating Objects using Paste Special Dialog
Box
To create OLE objects at run time, you use the OLE
control. It provides the methods listed in table T.7.1 to
create objects.
OLE Control Method Use

202
Displays the standard OLE
Insert Object dialog box to
[Link]
enable the user to select an OLE
object to create
Creates an embedded object in
[Link]
code without displaying the
file [, type]
OLE Insert Object dialog box

Creates a linked object from a


[Link] file file without displaying the OL
E Insert Object dialog box

Table T.7.1
Follow these steps to create an OLE object at run time:
1. Draw an OLE control on a form. VB displays the
standard Insert Object dialog box (Fig F.7.6).

Fig F.7.6

203
To create a linked or embedded object at run time,
click the Insert Object dialog box's Cancel button.
1. Click Cancel to close the Insert Object dialog
box without selecting an OLE object to
create.
2. In an event procedure, use the InsertObjDlg,
CreateEmbed, or CreateLink methods to
create an object for the control, as in the
following example:
Private Sub OLE1_DblClick()
' Let the user choose an object to create.
[Link]
End Sub

Creating an Embedded Object

To create an embedded object without displaying the


Insert Object dialog box, follow the procedure in the
preceding section, but substitute this code in step 3:
Private Sub OLE1_DblClick()
[Link] "", "[Link]"
' Create a new embedded Excel worksheet.
End Sub
The preceding lines of code embed a new, empty
worksheet in the OLE control OLE1. To base the
embedded object on a file, specify the file name in the
first argument, as in the following example:
Private Sub OLE1_DblClick()
[Link] "c:\excel\[Link]" '

204
Embed [Link].
End Sub
If you specify a file name for CreateEmbed, Visual
Basic ignores the second argument. If a file contains
more than one type of object, Visual Basic simply uses
the first object in the file. You cannot specify an object
within a file by using CreateEmbed.

Moving and Sizing Embedded Objects


By default, Visual Basic prevents from moving
embedded objects while they are being edited in place.

Fig. F.7.7
When you try to move or resize an embedded object, it
"snaps back" to its original position.

205
To enable users to move or size OLE objects at run
time, use the ObjectMove event procedure.
ObjectMove has the following form:
Private Sub OLE1_ObjectMove(Left As
Single, Top As Single, _
Width As Single, Height As Single)
'...your code here
End Sub
The arguments to the ObjectMove event procedure are
the position and dimensions to which the user dragged
the object. To make the object respond to the user's
action, simply assign the ObjectMove arguments to the
OLE control's Left, Top, Width, and Height properties,
as follows:
Private Sub OLE1_ObjectMove(Left As
Single, Top As Single, _
Width As Single, Height As Single)
[Link] = Left
[Link] = Top
[Link] = Width
[Link] = Height
End Sub
Now when the user moves or resizes the OLE object,
the OLE control adjusts to the new size and location as
shown in figure F.7.8

206
Fig F.7.8

The ObjectMove event procedure enables the OLE


control to respond when the user moves or resizes an
embedded object.
7.7 Autosizing an OLE Control
After an OLE control is added to a form, the way to
handle OLE object insertions with the
[Link] are the possible values for the
SizeModeproperty:
✓ vbOLESizeClip—0 (the default); Clip. The
object is displayed inactual size. If the object
is larger than the OLE control, its image
isclipped by the control’s borders.
✓ vbOLESizeStretch—1; Stretch. The object’s
image is sized to fill theOLE control. (Note
that the image may not maintain the
originalproportions of the object.)

207
✓ vbOLESizeAutoSize—2; Autosize. The OLE
control is resized todisplay the entire object.
✓ vbOLESizeZoom—3; Zoom. The object is
resized to fill the OLEcontainer control as
much as possible while still maintaining the
originalproportions of the object.
Getting the OLE Automation Object from Linked
or Embedded Objects
Use the OLE control's Object property to get the OLE
Automation object from a linked or embedded object
on a form. Not all applications provide OLE
Automation objects. If an object does not support OLE
Automation, the Object property returns Nothing.
When working with OLE Automation objects, you
should create an object variable to contain the OLE
Automation object. For example, the following lines
of code declare an object variable and establish a
reference to an embedded worksheet when the form
loads:
Option Explicit
Dim mobjExcelSheet
Private Sub Form_Load()
' Embed a worksheet in the OLE control
named oleExcel.
[Link] "c:\excel\[Link]"
' Establish a reference to the OLE
Automation object for the
' embedded worksheet.
Set mobjExcelSheet = [Link]
End Sub

208
In the preceding example, the variable
mobjExcelSheet has module-level scope; that is, other
procedures in the module have access to the variable.
For instance, the following Click event procedure uses
the OLE Automation object mobjExcelSheet to print
the embedded worksheet:
Private Sub cmdPrintSheet()
[Link]
End Sub
Unlike other applications that support OLE
Automation, Microsoft Word requires the following
special syntax to get its OLE Automation object:
Set objVar = [Link]
This is used as special syntax because Word exposes
only the WordBasic language for OLE Automation.
When working with the Word OLE Automation
object, remember that methods and properties apply to
the current document, which might not be the one that
the OLE control is currently displaying.
The following lines of code establish a reference to the
WordBasic OLE Automation object:
Option Explicit
Dim mobjWordBasic
Private Sub Form_Load()
' Embed a Word document in the OLE control
named oleWord.
[Link]
"c:\docs\[Link]"
' Establish a reference to the OLE
Automation object for the

209
' embedded worksheet.
Set mobjWordBasic =
[Link]
End Sub
The following two event procedures demonstrate how
the WordBasic methods apply to the current
document.
' Open a new file in Word (changes the
current document).
Private Sub cmdOpenNew()
[Link]
End Sub
' Print the current document in Word.
Private Sub cmdPrintDocument()
[Link]
End Sub

[Link] & File System Controls

8.1 INTRODUCTION
This chapter is on the file system controls helps the
user in understanding the methodology of using them
for choosing disk files for application. It also gives a
detailed description of accessing files in VB.
8.2 FILE SYSTEM CONTROLS
The DriveListBox control is a specialized drop-down
list that displays a list of all the valid drives on the
user's system. The most important property of the

210
DriveListBox is the Drive property, which is set when
the user selects an entry from the drop-down list or
when you assign a drive string (such as "C:") to the
Drive property in code. You can also read the Drive
property to see which drive has been selected.
To make a DirListBox display the directories of the
currently selected drive, you would set
the Path property of the DirListBox control to
the Drive property of the DriveListBox control in
the Change event of the DriveListBox, as in the
following statement:
[Link] = [Link]
The DirListBox control displays a hierarchical list of
the user's disk directories and subdirectories and
automatically reacts to mouse clicks to allow the user
to navigate among them. To synchronize the path
selected in the DirListBox with a FileListBox, assign
the Path property of the DirListBox to
the Path property of the FileListBox in
the Change event of the DirListBox, as in the
following statement:
[Link] = [Link]
The FileListBox control lists files in the directory
specified by its Path property. You can display all the
files in the current directory, or you can use
the Pattern property to show only certain types of
files.

211
Similar to the standard ListBox and
ComboBox controls, you can reference
the List, ListCount, and ListIndex properties to
access items in a DriveListBox, DirListBox, or
FileListBox control. In addition, the FileListBox has
a MultiSelect property which may be set to allow
multiple file selection.
The following program shows the selection of file
from [Link] selecting desired file, a
message box is displayed which displays the name of
the selected file. The application is designed as in the
following form.
All controls are added as in the form below and is
shown figure F.8.2.1

212
Fig F.8.2.1
Then the coding is added for each control as follows.
Private Sub Combo1_Change()
Select Case [Link]
Case 0
[Link] = "*.*"
Case 1
[Link] = "*.DOC"
Case 2
[Link] = "*.TXT"
End Select
End Sub
Private Sub Dir1_Change()
[Link] = [Link]
[Link] = [Link]

213
End Sub
Private Sub Drive1_Change()
On Error GoTo ErrorTrap
[Link] = [Link]
Exit Sub
ErrorTrap:
MsgBox "Drive Error", vbExclamation, "Error"
[Link] = [Link]
Exit Sub
End Sub
Private Sub File1_Click()
[Link] = [Link]
End Sub
Private Sub Form_Load()
[Link] "All Files(*.*)"
[Link] "Doc Files(*.DOC)"
[Link] "Text Files(*.TXT)"
[Link] = 0
[Link] = [Link]
End Sub
Private Sub Label5_Click()
End
End Sub

Private Sub ok_Click()


If [Link] = "" Then
MsgBox "No file was selected"
Else
MsgBox "Selected file is" + [Link]
End If

214
End Sub
After that the project get run displays the output as
follows.

Fig. F.8.2.2

8.3 ACCESSING FILES


As far as Visual Basic 6 is concerned; there are three
modes in which a file can be accessed.
1) Text Mode (Sequential Mode)
2) Random Access Mode
3) Binary Mode
In the Text Mode, data is ALWAYS written and
retrieved as CHARACTERS.
Hence, any number written in this mode will result in
the ASCII Value of the

215
number being [Link] Example, The Number 17 is
stored as two separate characters "1" and "7" which
means that 17 is stored as [49 55] and not as [17].
In the Binary Mode, everything is written and
retrieved as a Number. Hence, The Number 17 will be
stored as [17] in this mode and characters will be
represented by their ASCII Value as always.
One major difference between Text Files and
Binary Files is that Text Files support Sequential
Reading and Writing. This means that we cannot read
or write from a particular point in a file. The only way
of doing this is to read through all the other entries
until you reach the point where you want to 'actually'
start reading. Binary Mode allows us to write and read
anywhere in the file. For example we can read data
directly from the 56th Byte of the file, instead of
reading all the bytes one by one till we reach 56.
Just like the Binary Mode, the Random Access
Mode allows us to gain instant access to any piece of
information lying anywhere in the file at a cost.
In this case, we must standardize each piece of
information. For example, if we need to store a few
names in the file Random Access Mode requires us to
mention the length of the 'Names' Field.
Some Names might not fit and for the shorter names
the space is inefficiently used. Random Access Mode
allows us to read or write data at a particular record
position rather than a byte position like in Binary
Mode.
A Good Example of Sequential Mode is the Audio

216
[Link] we have tolisten to a particular Song in the
cassette, we have to play the tape right from the
beginning until we reach the beginning of the song.
And so obviously, CDs, DVDs etc. are examples of
Binary Mode.

8.3.1 SEQUENTIAL FILE HANDLING


To open a File in Sequential Mode, we need to use the
Open Command like this:
Open <FILENAME> For <MODE> As <FILE#>
FILENAME : Contains the Path of the File to be
opened.
MODE: Can be INPUT, OUTPUT or APPEND
FILE#: Any number from 1 to 255 preceded by a #
Each File irrespective of its mode requires a file
handle(FILE#). All operations on the file are done
using the File Handle.
The File Handle can be any number from 1 to 255, and
this number is preceded by the # character. Files can
be opened in three modes in Sequential File Handling
Mode and they are used in different situations as
shown.
INPUT -> Used to Read from a File.
OUTPUT -> Used to Write to a File.
APPEND -> Used to Write to a File.
Hence, to open a file [Link] in Input Mode we
use the Open Command like this:
Open "C:\[Link]" For Input as #1
Notice that the path of the file is mentioned. If the path
is not mentioned, Visual Basic assumes the file to be

217
in the current directory.
To close the file we use the CLOSE Command like
this:
Close #1
This Closes the File referred to by File Handle 1. The
Close Command can also be called with no arguments,
but in this case it would close all open Files.
For the rest of this section, assume the [Link] file
to contain the following data:
"Sanchit",9811122233
"Friend",9812345634
"Enemy",9821630236
Now let try to read from this file. We can read each
line separately into a string by using the Line Input
Command. Take a look at this snippet:
Dim tmp as String
Open "C:\[Link]" For Input as #1
Line Input #1, tmp
Close #1
Msgbox tmp
As you can see, the MessageBox displays:
“Sanchit”,9811122233
The Line Input Command extracts the line currently
pointed to by the File Pointer (this happens internally)
into a string. If we add another Line Input Command
after the first, the MessageBox willdisplay: "Friend",
9812345634. We can now write a Program that
displays the entire contents of a file in a MessageBox,
using the Line Input Command.
Dim tmp as String, contents as String

218
Open "C:\[Link]" For Input as #1
While Eof(1) = 0
line input #1,tmp
contents = contents + tmp
Wend
Close #1
Msgbox contents
The Output is:
"Sanchit",9811122233"Friend",9812345634"Enemy",
9821630236
The Eof() Function determines if the End of the
specified file has been reached.
If you look at the original file, there are newline
characters after every entry. But when we use Line
Input or any other Sequential Mode Function, the
Newline character is never considered. Hence the
Output shown is without the Newline Characters.
Now what if we wanted to separate the two fields and
store the Name and Phone Number into two variables,
we use with the help of the Input #<File> Command.
SYNTAX :
Input#<file_handle>,<var1>,[var2],…[varN]
To use the Input# Command, we must know the exact
number and type of fields present in a data file.
Remember that in case the argument types are
mismatched, it results in an Error.
As we have seen earlier, there are two modes for
writing data into a file, OUTPUT mode
and APPEND [Link] OUTPUT Mode creates a
new file irrespective of whether a file with the

219
samename exists or not. In other words, If no file by
the specified filename is present, a new file is created
else the previous file is overwritten.
The APPEND Mode does exactly what the OUTPUT
Mode does but with a difference. It can also create a
file if it doesn't exist in the directory. But if the file is
present, it adds data (provided by the programmer) to
the end of the file. This means that we can add new
information without destroying the information that
was present before. This mode can be used in a Web-
Access Logger Program. Everytime a User accesses
a webpage, the program can add the visitor's IP
Address to a given file. If the OUTPUT Mode was
used in this case, only the most recent visitor's IP
Address would be stored in the file.

Unlike Reading from Files which is done by using


only the Input# Command,
Writing to a File can be accomplished by using two
commands, Print# and Write#.
Their Syntax is exactly like that of the Input#
Command.
Consider the following code snippet:
Open "C:\names_database.txt" For Output As #1
Print #1, "My Phone number is 12345678", 910
Write #1, "My Phone number is 12345678", 910
Close #1
End
If you open the names_database.txt file in a Text-
Editor you will see the contents of the file as follows:

220
My Phone number is 12345678 910
"My Phone number is 12345678",910
With Print#, what appears in the file would be the
exact image of what would appear on the screen (i.e.
No quotes around strings and no commas)In this case
the file will contain the string: "My Phone number is
12345678" followed by 2 spaces, numeral 9, numeral
1, numeral 0, another space followed by two
characters (0xD 0xA) That make up the Carriage
Return/Line Feed Combination.
The Write# Command Writes Strings into the File
with the Quotes, Numbers as they are and separates
different fields by using a comma. It is good practice
to use this command instead of Print# since the Input#
Command is able to separate Records into Fields from
Records that are written by the Write# Command. (It
can work with Print# too, but it requires additional
code and yet may not work as expected)
We must remember one important thing about Print#
and Write#. After every Print#
or Write# Command, the respective command
automatically inserts a Carriage
Return/Line Feed Characters (0xD 0xA) and hence
every subsequent Write# or Print#
Command will write data to the next line in the file. If
you wish to write data
on the same line in the file, add it to the same
Print#/Write# Command.
Example:
Write #1,"ABCD"

221
Write #1,123
Write #1,"ABCD",123
OUTPUT:
"ABCD"
123
"ABCD", 123
Write# has a major advantage over Print# when it
comes to Storage of Strings. In the previous example,
the string:"My Phone number is 12345678" was stored
as "My Phone number is 12345678 " (with two
additional spaces) by using Print#. Sometimes 7
Additional Spaces are stored, at times 3 or 5 and the
number varies with each string. Hence it becomes
difficult to figure out if the 'additional' spaces are
actually a part of the string or are added by VB itself.
This also makes it difficult to separate a record into
different fields. The Write# Command on the other
hand stores the entire string within quotes, so there is
no doubt about the content as well as the length of the
string.

SEQUENTIAL FILE HANDLING FUNCTIONS

• FreeFile()
DESCRIPTION : Returns an Integer representing the
next file number available for use by the Open
statement.
SYNTAX : FreeFile[(rangenumber)]
The optional range number argument is a Variant that
specifies the range from which the next free file

222
number is to be returned. Specify a 0 (default) to
return a file number in the range 1 – 255, inclusive.
Specify a 1 to return a file number in the range 256 –
511.

USE : FreeFile() is used to avoid using a file handle


that is already
in use.
• EOF()
DESCRIPTION : Returns anInteger containing the
Boolean value True when the end of a file opened for
sequential Input has been reached.
SYNTAX : EOF(filenumber)
The required filenumber argument is an Integer
containing any valid file number.
USE: EOF() is occasionally used in loops to process a
file until the End of File is reached.
• FileLen()
DESCRIPTION : Returns a Long specifying the
length of a file in bytes.
SYNTAX : FileLen(pathname)
The required pathname argument is a string expression
that specifies a file.
USE : FileLen() is Used to find the length of a file that
has not been opened using the Open Command.
• LOF()
DESCRIPTION : Returns a Long representing the
size, in bytes, of a file opened using the Open
statement.
SYNTAX: LOF(filenumber)

223
The required filenumber argument is an Integer
containing a valid file number.
USE: LOF() is used to find the length of a file when a
file is
currently open.
• Seek()
DESCRIPTION : Returns a Long specifying the
current read/write position
within a file opened using the Open statement.
SYNTAX : Seek(filenumber)
The required filenumber argument is an Integer
containing a valid file number.
USE : Seek() is used to get the Byte Position where
the Next Operation will take place.
SEQUENTIAL FILE HANDLING EXAMPLES
Example 1: Getting the Number of Lines in a File.
Dim counter As Long, tmp As String
counter = 0
Open "c:\names_database.txt" For Input As #1
While Not EOF(1)
Line Input #1, tmp
counter = counter + 1
Wend
Close #1
MsgBox counter ' Outputs the Number of Lines
' in a File.
Example 2: Deleting a Record From a File (Using
Delete...Rename Method)
ASSUMPTION : The File [Link] contains:
"Sanchit", "Karve"

224
"ABCD", "PQRS"
"Steve", "Jackson"
"XYZ", "DEF"
CODE:

Dim delFirstName As String ' String that contains


Record to be Deleted
Dim fName As String, lName as String
delFirstName = "Sanchit"
Open "c:\[Link]" For Input As #1
Open "c:\[Link]" For Output As #2
While Not EOF(1)
Input #1, fName, lName
If fName <> delFirstName Then
Write #2, fName, lName
End If
Wend
Close #1, #2
Kill ("c:\[Link]") ' Deletes the Original File
Name "c:\[Link]" As "c:\[Link]"
' Renames the New File
Example 3: Deleting a Record from a File (Using
Arrays Only Method)
ASSUMPTION: The File [Link] contains:
"Sanchit"
"ABCD"
"Steve"
"XYZ"
CODE:
Dim strdelstring As String, tmp As String

225
Dim file_length As Long, i as Long
strdelstring = "Steve"
file_length = 0
Open "C:\[Link]" For Input As #1

' First We Find the Number of Records so that we can


allocate an Array
' To Accomodate all records
While Not EOF(1)
Line Input #1, tmp
file_length = file_length + 1
Wend
Close #1
' Now allocate the Array
ReDim arrdata(file_length) As String
' And Store the Entire File's Contents into the Array
Open "c:\[Link]" For Input As #1
For i = 1 To file_length
Input #1, arrdata(i)
Next i
Close #1
' Now Open the Same File Again in Output Mode and
Write the Contents
' Back into the File except that which is supposed to be
deleted.
Open "c:\[Link]" For Output As #1
For i = 1 To file_length
If arrdata(i) <> strdelstring Then
Write #1, arrdata(i)
End If

226
Next i
Close #1
Example 4: Storing/Reading a User Defined Type
in a String
STORING:
Dim x As Student, y As Student
[Link] = "Nerd"
[Link] = 18
[Link] = "A+"
[Link] = "Dunce"
[Link] = 18
[Link] = "F"
Open "c:\[Link]" For Output As #1
Write #1, [Link], [Link], [Link]
Write #1, [Link], [Link], [Link]
Close #1
READING:
Dim x As Student, y As Student
Open "c:\[Link]" For Input As #1
Input #1, [Link], [Link], [Link]
Input #1, [Link], [Link], [Link]
Close #1
MsgBox [Link] + " " + Str([Link]) + " " + [Link]
MsgBox [Link] + " " + Str([Link]) + " " + [Link]

BINARY FILE HANDLING


In the Binary Mode, everything is written and
retrieved as a Number. Hence, The Number 17 will be
stored as [17] in this mode and characters will be
represented by their ASCII Value as always. One

227
major difference between Text Files and Binary Files
is that Text Files support Sequential Reading and
Writing. This means that we cannot read or write from
a particular point in a file. The only way of doing this
is to read through all the other entries until you reach
the point where you want to 'actually' start reading.
Binary Mode allows us to write and read anywhere in
the file. For example we can read data directly from
the 56th Byte of the file, instead of reading all the
bytes one by one till we reach the 56th byte.
Let us start with a very simple example:
'Add a Command Button with name as Command1
onto a Form
Private Sub Command1_Click()
Dim f As Long
f = FreeFile()
Open "c:\[Link]" For Binary As #f
Close #f
End Sub
As you can see, the FreeFile() function can also be
used for binary files. The Open Statement opens
c:\[Link] in Binary Mode and the next statement
closes the file.
As obvious as it may sound, you need to open a file
before using it and close it when you have finished
reading or writing to it. Many programmers forget to
add the Close statement which results in the File
Already Open Error, and it can be a pain to track down
the exact location that caused the error when you're
dealing with many files.

228
You should note that this snippet does more than open
and close a file. If the [Link] file is not present in C
drive, then it creates a blank file with the same name.
8.3.2 READING AND WRITING IN BINARY
MODE
Now that you know how a file is opened, let us see
how we can read and write data in Binary mode.
Here's an example which writes a string in a Binary
File.
'Create a Command Button as Command1
Private Sub Command1_Click()
Dim f As Long
f = FreeFile()
Open "C:\[Link]" For Binary As #f
Put #f, , "This is the Test file."
Close #f
End Sub
The string "This is the Test file." is written to the
[Link] file in the C drive. The Put Statement is used to
write data to a binary file. The Syntax of Put is as
follows:
Put #fileNumber, [startByte], varName
where
#fileNumber = A file handle ('f' is the file handle in the
previous example)
startByte = (Optional) Byte position to start writing at.
varName = Variable/Literal whose contents are to be
written. varName can be a variable of any data type. In
the above example, we have skipped the second
parameter which means that the string is written at the

229
current position of the file, which in this case is the
beginning of the file.
We can choose to write data at a different position by
specifying this [Link] the Put Statement
from the previous example to Put #f,13,”B” .
Now if we run the program and then open the [Link]
file. Now the file contains the content as "This is the
Best file." The Put statement in this case writes "B" at
the 13th byte in the file. We can see that the 13th
position in the file is the letter "T". Hence "T" gets
replaced by "B".
A logical opposite of Put is Get, and that's what you'll
need to use to read data from a Binary File.
Private Sub Command1_Click()
Dim f As Long
Dim x As Byte
f = FreeFile()
Open "C:\[Link]" For Binary As #f
Get #f, , x
Close #
MsgBox x
End Sub
This will display 84 (ASCII Value of T) in a Message
Box. The syntax of the Get Statement is exactly the
same as that of the Put statement. Experiment with the
second parameter and notice how you get ASCII
values of the elements.
Let's try to read in the first word of the file. We know
that the first word is"This", so we'll create a Byte
Array of length 4 like this:

230
Private Sub Command1_Click()
Dim f As Long
Dim x(3) As Byte 'Creates Array from Index 0 to 3
Dim readresult As String
f = FreeFile()
Open "C:\[Link]" For Binary As #f
Get #f, , x
Close #f
readresult = Chr(x(0)) & Chr(x(1)) & Chr(x(2)) &
Chr(x(3))
MsgBox readresult
End Sub
Visual Basic will automatically fill in every element of
the array x until it can't store any more. So it starts
from the first position (2nd parameter is not specified)
and copies the first 4 characters into the Byte Array x.
Since the array x is of data type Byte, we need to
convert it to a string and then display it as shown.
Private Sub Command1_Click()
Dim f As Long
Dim readresult As String
f = FreeFile()
Open "C:\[Link]" For Binary As #f
Get #f, , readresult
Close #f
MsgBox readresult
End Sub
The output of this code is totally unexpected. It is null.
The Message Box doesn't display anything. Because
the Get statement automatically detects the length of

231
the string and fills up data into the variable till it store
any more.
The length of the readresult string is zero because
nothing is stored in it initially, and hence nothing will
be stored in it after the Get statement. To get the code
to work as expected, we need to specify the length of
the string by either defining it as a fixed-length string
or initializing it to a string of non-zero length.
We can either define the string as a fixed-length string
like this:
Dim readresult As String * 4
or initialize the string to something with its length as
4 like this:
Dim readresult As String
readresult = String(4, " ") ' or even readresult =
"ABCD"
Now, make the appropriate changes in the previous
example and run the program. The Message Box
should display "This".

8.3.3Random Access Files


It should be noted that to access a particular data item in
a sequential file, you need to read in all items in the file
prior to the item of interest. This works acceptably well
for small data files of unstructured data, but for large,
structured files, this process is time-consuming and
wasteful. Sometimes, we need to access data in
nonsequential ways. Files which allow nonsequential
access are random access files.
To allow nonsequential access to information, a random

232
access file has a very definite structure. A random access
file is made up of a number of records, each record
having the same length (measured in bytes). Hence, by
knowing the length of each record, we can easily
determine (or the computer can) where each record
begins. The first record in a random access file is Record
1, not 0 as used in Visual Basic arrays. Each record is
usually a set of variables, of different types, describing
some item. The structure of a random access file is:

Record 1
Record N
Record 2
Record N
Record 3
Record N
.
.
Record Last
N Bytes

A good analogy to illustrate the differences between


sequential files and random access files are cassette
music tapes and compact discs. To hear a song on a
tape (a sequential device), you must go past all songs
prior to your selection. To hear a song on a CD (a
random access device), you simply go directly to the
desired selection. One difference here though is we

233
require all of our random access records to be the same
length - not a good choice on CD’s!
To write and read random access files, we must know the
record length in bytes. Some variable types and their
length in bytes are:
Type Length (Bytes)
Integer 2
Long 4
Single 4
Double 8
String 1 byte per character
So, for every variable that is in a file’s record, we need to
add up the individual variable length’s to obtain the total
record length. To ease this task, we introduce the idea of
user-defined variables.
user-defined variables
Data used with random access files is most often stored
in user-defined variables. These data types group
variables of different types into one assembly with a
single, user -defined type associated with the group.
Such types significantly simplify the use of random
access files. The Visual Basic keyword Type signals
the beginning of a user-defined type declaration and the
words End Type signal the end. An example best
illustrates establishing a user-defined variable. Say we
want to use a variable that describes people by their
name, their city, their height, and their weight. We
would define a variable of Type Person as follows:
Type Person
Name As String

234
City As String
Height As Integer
Weight As Integer
End Type
To create variables with this newly defined type, we employ
the usual Dim statement. For our Person example, we
would use:
Dim Lou As Person
Dim John As Person
Dim Mary As Person
And now, we have three variables, each
containing all the components of the variable type
Person. To refer to a single component within a user-
defined type, we use the dot-notation:
[Link]
As an example, to obtain Lou’s Age, we use:
Dim AgeValue as Integer
.
.
AgeValue = [Link]
Note the similarity to dot-notation we’ve been using to set
properties of various Visual Basic tools.
Writing and Reading Random Access Files
We look at writing and reading random access
files using a user -defined variable. For other variable
types, refer to Visual Basic on-line help. To open a
random access file named RanFileName, use:
Open RanFileName For Random As #N Len =
RecordLength
where N is an available file number and RecordLength is

235
the length of each record. Note you don’t have to specify
an input or output mode. With random access files, as long
as they’re open, you can write or read to them.
To close a random access file, use: Close
As mentioned previously, the record length is the
sum of the lengths of all variables that make up a record. A
problem arises with String type variables. You don’t
know their lengths ahead of time. To solve this problem,
Visual Basic lets you declare fixed lengths for strings. This
allows you to determine record length. If we have a string
variable named StrExample we want to limit to 14
characters, we use the declaration:
Dim StrExample As String * 14
Recall each character in a string uses 1 byte, so the length
of such a variable is 14 bytes. Recall our example user-
defined variable type, Person. Let’s revisit it, now with
restricted string lengths:
Type Person
Name As String * 40
City As String * 35
Height As Integer
Weight As Integer
End Type
The record length for this variable type is 79 bytes
(40 + 35 +2 + 2). To open a file named PersonData as
File #1, with such records, we would use the statement:
Open PersonData For Random As #1 Len = 79
The Get and Put statements are used to read from and
write to random access files, respectively. These
statements read or write one record at a time. The

236
syntax for these statements is simple:
Get #N, [RecordNumber], variable
Put #N, [RecordNumber], variable
The Get statement reads from the file and stores data in
the variable, whereas the Put statement writes the
contents of the specified variable to the file. In each case,
you can optionally specifiy the record number. If you do
not specify a recordnumber, the next sequential position is
[Link] variable argument in the Get and Put statements
is usually a single user- defined variable. Once read in,
you obtain the component parts of this variable using dot-
notation. Prior to writing a user-defined variable to a
random access file, you ‘load ’ the component parts using
the same dot-notation.
There’s a lot more to using random access files;
we’ve only looked at the basics. Refer to your Visual
Basic documentation and on-line help for further
information. In particular, you need to do a little cute
programming when deleting records from a random
access file or when ‘resorting’ records.

237
UNIT V
[Link] CONTROLS IN VB
Memory Organization: Memory Hierarchy –Main
Memory-Associative memory: Hardware
Organization, Match Logic, Read Operation, Write
Operation. Cache Memory: Associative, Direct, Set-
associative Mapping –Writing into Cache
Initialization.

9.1 INTRODUCTION
The Advanced Visual Basic toolbox controls and
teaches the end users how to use them to build useful
interface features. In this introduction part, the end
users will learn how to:
• Name Visual Basic objects.
• Use basic controls to display text and process input.
• Use file system controls to browse the files and
folders on your computer.
• Use data input controls to display lists and check
boxes.

Visual Basic concepts


Control
A control is a tool you use to create objects on a
Visual Basic form. You select controls from the
toolbox and use the mouse to draw objects on a form.
You use most controls to create user interface

238
elements, such as command buttons, image boxes, and
list boxes.
Object
An object is a type of user interface element you create
on a Visual Basic form by using a toolbox control. (In
fact, in Visual Basic, the form itself is also an object.)
You can move, resize, and customize objects by
setting object properties. Objects also have what is
known as inherent functionality — they know how to
operate and can respond to certain situations on their
own. (A list box “knows” how to scroll, for example.)
You can customize Visual Basic objects by using
event procedures that are fine-tuned for different
conditions in a program.
Property
A property is a value or characteristic held by a Visual
Basic object, such as Caption
or
Fore Color
Properties can be set at design time by using the
Properties window or at run time by using statements
in the program code. In code, the format for setting a
property is:
Object. Property = Value
Where,
Object is the name of the object you’re customizing.
Property is the characteristic you want to change.
Value is the new property setting.
For example,
[Link] = "Hello"

239
Could be used in the program code to set the Caption
property of the Command1 object to “Hello”.
Event Procedure
An event procedure is a block of code that runs when a
program object is manipulated.
For example, clicking the first command button in a
program executes the Command1_Click event
procedure. Event procedures typically evaluate and set
properties and use other program statements to
perform the work of the program.

Program Statement
A program statement is a combination of keywords,
identifiers, and arguments in the code that does the
work of the program.
Visual Basic program statements create storage space
for data, open files, perform calculations, and do
several other important
tasks.
Method
A method is a special keyword that performs an action
or a service for a particular program object. In code,
the format for using a method is,
Object. Method Value

Where,
Object is the name of the object you are working with.
Method is the action you want the object to perform.

240
Value is an optional argument to be used by the
method.
For example, this statement uses the
Add Item method to put the word Check in the List1
List box:
[Link] "Check"
Variable
A variable or identifier is a special container that holds
data temporarily in a program.
You create variables to store calculation results, create
file names, process input, and so on. Variables can
store numbers, names, property values, and references
to objects.
Naming Visual Basic Objects
You may be a Visual Basic beginner now, but that
won’t be true for long. As your programs increase in
size and sophistication, the number of objects you use
on your forms will multiply quickly. There is an easy
way to avoid mistaking one object for another in the
Properties window or in your program code: assigning
a unique name to each object soon after you creates it.
It’s simple — when you set your other object
properties, just click the (Name) property, and then
givethe object a unique name.

9.2 SSTAB CONTROL


Tab Property (SSTab Control)
Returns or sets the current tab for an SSTab control.

Syntax

241
[Link] [ = tabnumber ]
The Tab property syntax has these parts:

Typically, the user of your application clicks a tab to


make it the current tab. However, you may need to
select the current tabin code. For example, you may
want the same tab to be the current tab each time you
display a certain dialog box in your application. If you
dismiss the dialog box by using the Hide method of
the Form, the last tab to be the active tab when the
Form was hidden will be the active tab the next time
the dialog box appears. You can set the Tab property
of the SSTabcontrol so the same tab is active every
time the dialog box appears. This example always
makes the first tab in the SSTab control the active tab
just before showing the form which contains the
control. To try this example, create two Form objects.
Place a CommandButton control on Form1 and an
SSTab control onForm2. Paste the code into the Click
event of the CommandButton on Form1, and then run
the example.
Private Sub Command1_Click()
[Link] = 1
[Link]
End Sub

242
TabCaption Property (SSTab Control)\
Syntax
[Link](tab) [ = text ]
The TabCaption property syntax has these parts:

At design time, you can set the TabCaption property


by clicking a tab and then setting the Caption property
in theProperties window. Or you can select (Custom)
in the Properties window and set the TabCaption
property in the General tabof the Properties dialog
[Link] run time, you can read or change the caption of
any tab using the TabCaption property.
You can also use the Caption property to change the
TabCaption property for just the active [Link] can
use the TabCaption property to assign an access key to
a tab. In the TabCaption setting, include an ampersand
(&) immediately preceding the character you want to
designate as an access key.
The character is underlined. Press the ALT keyplus
the underlined character to make that tab the active tab.
To include an ampersand in a caption without creating
an access key, include two ampersands (&&). A single

243
ampersand is displayed in the caption and no
characters are [Link] example adds or
removes an extra word from the tabs of an SSTab
control that lists the defensive players of a sport on one
tab and the offensive players on another tab. By
clicking the CheckBox control on the Form, the user
can togglebetween longer captions or shorter ones.

Private Sub Check1_Click()


Dim X As Integer
For X = 0 To [Link] - 1
Select Case [Link]
Case 0 ' Toggle to short captions.
[Link](X) =
Left([Link](X), 7)
Case 1 ' Toggle to long captions.
[Link](X) = [Link](X) & "
Players
End Select
Next X
End Sub

TabEnabled Property (SSTab Control)


Returns or sets a value that determines whether a tab in
an SSTab control is available when clicked.

Syntax

[Link](tab)[ = boolean ]
The TabEnabled property syntax has these parts:

244
Part Description

When a tab is disabled, the text on the tab appears


dimmed and the user cannot select that tab. The
TabEnabled property enables or disables a single tab.
Use the Enabled property to enable or disable the
entire SSTab control.

TabFixedHeight, TabFixedWidth Properties

Return or set the fixed height and width of all Tab


objects in a TabStrip control, but only if the
TabWidthStyle property is set to tabFixed.

Syntax
[Link] [= integer]
[Link] [= integer]
The TabFixedHeight and TabFixedWidth properties
syntax has these parts:

245
The TabFixedHeight property applies to all Tab
objects in the TabStrip control. It defaults either to the
height of the font asspecified in the Font property, or
the height of the ListImage object specified by the
Image property, whichever is higher,plus a few extra
pixels as a border. If the TabWidthStyle property is set
to tabFixed, and the value of the TabFixedWidth
property is set, the width of each Tab object remains
the same whether you add or delete Tab objects in the
control.

TabHeight Property (SSTab Control)


Returns or sets the height of all tabs on an SSTab
control.
Syntax
[Link] [ = height ]
The TabHeight property syntax has these parts:

246
Tab Index Property
Returns or sets the tab order of most objects within
their parent form.

Syntax
[Link] [= index]
The TabIndex property syntax has these parts:

By default, Visual Basic assigns a tab order to controls


as you draw them on a form, with the exception of the
Menu, Timer, Data, Image, Line and Shape controls,
which are not included in the tab order. At run time,
invisible or disabled controls and controls that can't
receive focus (Frame and Label controls) remain in
the tab order but are skipped during tabbing. Each new
control is placed last in the tab order. If you change the
value of a control's TabIndex property to adjust the
default tab order, Visual Basic automatically
renumbers the TabIndex of other controls to reflect
insertions and [Link] can make changes at
design time using the Properties window or at run time
in code

247
The TabIndex property isn't affected by the ZOrder
method. Note A control's tab order doesn't affect its
associated access key. If you press the access key for a
Frame or Label control, the focus moves to the next
control in the tab order that can receive the focus.
When loading forms saved as ASCII text, controls
with a TabIndex property that aren't listed in the form
description are automatically assigned a TabIndex
value. In subsequently loaded controls, if existing
TabIndex values conflict with earlier assigned values,
the controls are automatically assigned new values.
When you delete one or more controls, you can use the
Undo command to restore the controls and all their
properties except for the TabIndex property, which
can't be restored. TabIndex is reset to the end of the
tab order when you use [Link] example reverses
the tab order of a group of buttons by changing the
TabIndex property of a command button array. To try
this example, paste the code into the Declarations
section of a form that contains four CommandButton
controls. Set the Name property to CommandX for
each button to create the control array, and then press
F5 and click the form to reverse the tab order of the
buttons.

Private Sub Form_Click ()


Dim I, X ' Declare variables.
' Reverse tab order by setting start value of X.
If CommandX(0).TabIndex = 0 Then X = 4 Else X = 1

248
For I = 0 To 3
CommandX(I).Caption = X ' Set caption.
CommandX(I).TabIndex = X - 1 ' Set tab order.
If CommandX(0).TabIndex = 3 Then
X = X - 1 ' Decrement X.
Else
X = X +1 ' Increment X.
End If
Next I
End Sub

9.3 SETTING PROPERTIES AT RUNTIME


Many Visual Basic programmers are aware that it's
possible to create controls at runtime by first creating a
control array, and then adding additional members to
the control array at runtime by using the Load
Statement. This is the first method I'll be examining in
this article. In addition, I'll also show you how can
create controls at runtime entirely from scratch,
without the need to first create a control array.

Method 1---Using a Control Array to create


controls
To create a control at run time using this method you
first must create a control array for the control you
wish to dynamically create. In other words, if you want
to create checkboxes at run time, you first must create
a control array of checkboxes.
In the Command Button, I'll be placing code to

249
dynamically create a checkbox on the form at run time.
More on that in a few minutes. First,We need to tell
Visual Basic that the Checkbox is a member of a
Control Array---I do that merely by changing its Index
property from the default blank value to a number---in
this case 0.

Once the Index property has been set to 0, the


Checkbox is now a member of the Check1 Checkbox
Control Array---which makes creating a new checkbox
at runtime very easy. All we need to do is tell Visual
Basic that we want to create a new checkbox, using the
existing Checkbox as a template. We do this by
executing the Visual Basic Load Statement within the
Click Event Procedure of the Command Button like
this.

Private Sub Command1_Click()


Load Check1(1)

250
Check1(1).Caption = "New Checkbox"
End Sub

The Load statement

Load Check1(1)

It tells Visual Basic to create a new member of the


Check1 checkbox array---and to create it with an Index
property of 1. This statement

Check1(1).Caption = "New Checkbox"

It gives the Checkbox, whose index property is equal


to 1, a unique caption to make it 'stand out' form the
original checkbox placed on the form at design time.
If we now run the program, and then click on the
Command Button we'll see this screenshot
By default, the Visible property of the new control is
set to False. To see the new control, we need to
explicitly set its Visible property to True. Let's modify
the code in the Click event procedure to look like this
as shown below.

251
Private Sub Command1_Click()
Load Check1(1)
Check1(1).Caption = "New Checkbox"
Check1(1).Visible = True
End Sub

The problem is this: when the new control is created,


the properties of the new control are identical to the
properties of the 'template' control used to create it
along with the exception of the Index property which
we set with the Load statement, and the Visible
property which we know is initialized to False.
Because of that, the new checkbox is on the form and
probably it just so happens to be sitting 'under' the first
control, since it has identical Top, Left, Height and
Width properties.
All we need to do to see the new control is to move it
away from the first control---and we can do that by
adding a line of code to the Click
Event procedure to change the Top property of the
new control. Similar to the given code.

Private Sub Command1_Click()


Load Check1(1)
Check1(1).Caption = "New Checkbox"
Check1(1).Visible = True
Check1(1).Top = Check1(0).Top + Check1(0).Height
End Sub

The code:

252
Check1(1).Top=Check1(0).Top + Check1(0).Height

To tell VB to take the current value of the Top


property of the existing checkbox, and to add to that
the value of its Height Property (remember, the first
control has an Index property of 0). The result of this
addition is a Top property for the new control that is
just under the first control.
If we now run the program, and click on the Command
Button, we'll see this screen shot as shown in the next
page.

It should also pointed out that if we want to give the


user the impression that we are creating controls totally
from scratch, we can place the template control on the
form---and then set its Visible property to False---that

253
way, at run time, the controls are created and
seemingly out of no [Link] review, here’s a
summary of the steps necessary to create a new control
using the Control Array method.

1. Create a control array of the control type you wish


to create at runtime. If you want to create a textbox at
runtime, create a Textbox control array. If you want to
create a Command Button, create a Command Button
Control array. Remember, to create a Control Array,
all you need to do is to change the Index property of
the control to something other than its default empty
value.
2. Use the Load Statement, with a unique Index
property, to create the new control.
3. Change the Visible property of the new control to
True in order to make it visible.
[Link] the coordinate properties (Left or Top) to
bring the new control out from under the original.

Method 2---Creating controls from scratch using


the Controls Collection
There's a second method to create a control at runtime,
and that's to use the Add Method of the Controls
collection. This method is easier to use than the
Control Array method, but harder to understand since
it requires some familiarity with the Visual Basic
Controls Collection. (I discuss the Controls Collection
in my latest book, Learn To Program Objects with
Visual Basic 6.)

254
In short, each control that is placed on the form either
at Design time or runtime is made a member of the
intrinsic Visual Basic Collection called the Controls
Collection. For those of you not familiar with Visual
Basic Collections, a Collection is similar to a one
dimensional array.
Each control on the form has a reference placed on the
Controls collection when it is placed there at design
time. In the same way, a control that is placed on the
form at run time (the way we just did using the Control
Array Method) also has a reference placed on the
Controls Collection.
It's also possible to create a control at runtime by
adding a reference to a control directly to the Controls
Collection. Doing so avoids the necessity of first
having to create a 'template' control on the form at
design time---the reason for that is that VB maintains
templates for all of the controls in the hidden Visual
Basic Global Object called VB(again, more on this in
my Objects Book).Suffice to say that all that is
required to create a control at runtime using this
method is to execute four lines of code, like this…

Private Sub Command1_Click()


Dim ctlName As Control
Set ctlName =[Link]("[Link]",
"Text1", Form1)
[Link] = True
[Link] = Check1(0).Top + Check1(0).Height
End Sub

255
This line of code
Dim ctlName As Control

It declares something known as an Object Variable---


which is nothing more than a variable that contains, as
a value, a reference to anObject (in this case, a
Textbox). You can declare an Object variable as a
specific control type (such as Textbox) or elect to
declare it as the more generic Control type, which is
what we did here.
This line of code
Set ctlName = [Link]("[Link]",
"Text1", Form1)

It tells Visual Basic to add a Textbox control called


Text1 to the Controls. Collection of Form1, and to use
the Object Variable ctlname to 'point to it'. Once this
control has been added to the Controls Collection,
thereafter whenever we refer to the control using code
we must refer to it by the Object Variable Name.
That's why, when we then set theVisible property of
the new textbox to True, and adjust its Top property,
we use the Object Variable name instead.

[Link] = True
[Link] = Check1(0).Top + Check1(0).Height

More on the Add Method

256
The Add Method has three arguments---the first is the
name of the template for the control you are creating,
the second is the name of the control as it will appear
in the Controls Collection, and the third argument is
the control's container (ordinarily the form, but it could
be the name of a Frame Control if you wanted the
control to be placed'within' a Frame on the form).The
Textbox control is called Textbox, the Command
Button control is called CommandButton. If you open
the Visual Basic Object Browser (View-Object
Browser from the Visual Basic Menu Bar) and select
the VB Global Object in the library listbox.

257
Again, for more information on the Visual Basic
Object Browser, check out my Objects [Link] we now
run the program, and click on the command button,
we'll see this screenshot.

Creating Visual Basic Controls at Runtime

As you can see, the new Textbox control has been


placed on the form.

9.4 USING THE TABSTRIP CONTROL

258
Included with the Microsoft Windows common
controls meaning, part of the file Comet132.0cx—is a
TabStrip control. The Microsoft TabStrip control
works differently from the SSTab control. In my
opinion, it is not as user-friendly as the SSTab:
Code is required to make it work. Instead of having
access to individual tab pages at design time as with
the SSTab control, you must manipulate the TabStrip
pages with code at runtime. This means that you have
to place all control containers on what appears to be
the first tab page of the TabStrip control as shown in
the below figure. From there, using code, you can re-
size the containers to fit the client area of the tab page
and bring the correct container to the front using the
ZOrder method.

259
An example of a working TabStrip control with
picture box containers is available on the companion
CD-ROM as [Link]. Here's how to get the
TabStrip control to work. Start a new project and add a
TabStrip to a form, sizing it as you wish. Open the
TabStrip Control Properties windows found under the
Custom property and move to the Tabs tab page to set
up three tab pages. On the Tabs tab page enter a
caption for the first tab page, and then press the Insert
Tab button to create a second tab page. Enter a caption
for this tab page, and then create a third tab page by
again pressing the Insert Tab button. Add a caption for
that tab page, and then click OK to close the Properties
window. Add an array of three picture box controls to
act as containers to the TabStrip control, as shown
back in Figure 8-6. Add a different check box to each
picture box, and then open the form's Code window.
Add the following code to the form's Load event to
size the picture control array to cover the client area of
the tab control and set the first picture control on top:

Private Sub Form_Load()


Dim i As Integer
For i - 0 To 2
picContainer(i).Left = [Link]
picContainer(i).Top = [Link]
picContainer(i).Height =[Link]
picContainer(i).Width - [Link]
Next
picContainer(0).Z0rder 0

260
End Sub
Then, add a line of code to the TabStrip's Click event
to bring the correct picture control to the front when
the user changes tab pages:
Private Sub tabSundae_Click()
picContainer(tabDemo.SelectedItemAndex1).Z0rder 0
End Sub
Run the demonstration application now and see how
the picture boxes are resized and correctly brought to
the front when a specific tab page is selected.

Creating a Wizard

Visual Basic 6 Wizard Manager is a tool designed to


help you create Wizards that are add-ins. The user can
run Wizard wizard by selecting it from Visual Basic’s
Add Ins menu, provided that it first has been loaded in
the Add-Ins Manager. The primary purpose of the
Wizard Wizard is to manage the design time interface
of the Wizard panels, where the Wizard is intended to
be used as an add-in that interacts with instances of
the Visual Basic Environment.
Creating Your Own Wizards
Here's how you can use my generic Wizard to create
your own Wizards:
1. Copy the Wizard files —[Link], Wizard,Frm,
and [Link]—to your hard drive.
2. Open the [Link] project. Save each file, and
the project, under a new name.

261
3. Plan the number of panels you'd like and the
number of controls that will appear on each panel.
4. Open the [Link] code module in the Code
Editor. Find the SetUpWiz procedure. It will look like
this:
Private Sub SetUpWiz()
'Panel 1
ItemsInPanel 0
'Panel 2
ItemsInPanel 0
'Panel 3
ItemsInPanel 0
End Sub
The number of calls to ltemslnPanel represents the
number of panels in the Wizard; the argument passed
to ItemsInPanel tells the Wizard how many controls
are on that panel. The user needs to change the code to
reflect your particular Wizard. For example, if you
wanted to create a four –panel Wizard with two
controls on each panel, you would change SetUpWiz
to read as follows:
Private Sub SetUpWiz()
'Panel 1
ItemsInPanel 2
'Panel 2
ItemsinPanel 2
'Panel 3
ItemsInPanel 2
'Panel 4
ItemslnPanel 2

262
End Sub
5. Next, add the controls you'd like to the [Link].
The Wizard manages the visibility and invisibility of
these controls through their Tag properties, so it's
important that you set .Tag correctly. The first control
you add should have its .Tag property set to 5. (This
value is one more than the number of Wizard common
controls. Four controls appear on every panel: three
buttons and a line.)
The second control should have its .Tag property set to
6, and so on. You must set the Tag properties so the
panels are managed properly. In the example with two
controls per panel, the controls should have Tag
properties as shown in Table 8-2.
Table 8.2 Tag Properties for Controls on a Four-Panel
Wizard with Two Controls per Panel

6. That's it for managing the appearance of the panels.


You'll also want to add execution code that makes the
Wizard actually do something. Usually, this code is
called after the user clicks the Finish button. I've
added a procedure for you to use in this fashion. It's
called ShutDown and it has a message box as a
placeholder that's called when the user clicks Finish:

263
Public Sub ShutDown()
MsgBox "Doing what has to be done with values and
stuff...ending!"
Unload ThisWizard
End
End Sub

9.5 MSFLEXGRID CONTROL

The MSFlexGrid control displays and operates on


tabular data. it enables complete flexibility to sort,
merge, and format tables containing strings and
pictures. For example, you can make an MSFlexGrid
appear to be a spreadsheet. When bound to a Data
control. MSFlexGrid displays read-only data.

You can put text, a picture, or both in any cell of an


MSFlexGrid. The Row and Col properties specify the
current cell in an MSFlexGrid. You can specify the
current cell in code, or the user can change it at
runtime using the mouse or the arrow keys. The Text
property references the contents of the current cell.

If a cell's text is too long to be displayed in the cell,


and the WordWrap property is set to True, the text
wraps to the next line within the same cell. To display
the wrapped text, you may need to increase the cell's
ColWidth property or RowHeight property. You use
the Cols and Rows properties to set the total number of
columns and rows in an MSFlexGrid control.

264
Whenever you are doing any project, always a need
arises where you have to display the Data in a Tabular
Format. There are several Controls in VB6 Which can
take care of such displays. But, I have always found
MSFlexGrid come in handy. As the name itself
suggests, it is really a Flexible Grid. There are 2 ways
to display the Data in FlexGrid :

• DataBinding
• Manually

DataBinding is Done just by Adding a DataControl to


the Form and setting the DataSource Property of the
Grid to [Link] I will deal with the other
way, Which Includes a bit of Coding. It’s a visual treat
to see the Display of FlexGrid by changing the
Font/Color [Link] I will take a Simple
EmpMaster Table which Contains these Fields:

• EmpNo (Numeric)
• EmpName (Text(100))
• DOJ (Date)
• BasicSalary (Number)
• Allowances (Number)

Say, you have all the data loaded in the database. First
of all, Open a New Project Add this in Reference as
Microsoft Active-X Data Objects Library 2.0• (or any

265
higher version if u have.).
Now to Add MSFlexGrid: Goto Menu
Project>Components, Select MSFlexGrid Control 6.0.
Check it and Click [Link] the Grid will be loaded in
the ToolBox. Add the MSFlexGrid Control to your
Form and Rename it.
'Open the Connection say “AConn”•, Declare a
[Link] Object say RST. And query the
EmpMaster Table:

Dim TCurr As Currency


Dim i As Long
Dim sSQL As String
Dim RST As New [Link]
sSQL = “Select * From EmpMaster Order By
EmpName”
[Link] sSQL,AConn,dbOpen, adOpenStatic,
adLockReadOnly

'Load the Grid Using This Code:


i=0
With Grd
.Rows = 1
.Cols = 6
.TextMatrix(0,0) = “EmpNo”
.TextMatrix(0,1) = “Name”
.TextMatrix(0,2) = “JoinDate”•
.TextMatrix(0,3) = “BasicSalary”•
.TextMatrix(0,4) = “Allowances”
.TextMatrix(0,6) = “TotalSalary”

266
If Not [Link] Then
[Link]
Do While Not [Link]
i=i+1
Rows = i + 1
.TextMatrix(i, 0) =RST(“EmpNo”) & “ “
.TextMatrix(i, 1) =RST(“EmpName”) & “ “
.TextMatrix(i, 2) =RST(“DOJ”•) & “ “
.TextMatrix(i, 3) =RST(“BasicSalary”•) & “ “
.TextMatrix(i, 4) =RST(“Allowances”•) & “ “•
TCurr = Val(RST(“BasicSalary”) & “ “) ) +
Val(RST(“Allowances”•) & “ “•) .TextMatrix(i, 5) =
TCurr
[Link]
Loop
End If
End With

267
[Link] DATA OBJECT (ADO)
10.1 WHY ADO?
ActiveX Data Objects expose their properties by
means of COM interfaces; they can be accessed by
any language that can utilize COM. In this chapter we
will discuss how to access ADO from Visual Basic.
ActiveX Data Objects (ADO) is an application
program interface from Microsoft that lets a
programmer writing Windows applications get access
to a relational or non-relational database from both
Microsoft and other database providers. For example,
if you wanted to write a program that would provide
users of your Web site with data from an IBM DB2
database or an Oracle database, you could include
ADO program statements in an HTML file that you
then identified as an Active Server Page. Then, when a
user requested the page from the Web site, the page
sent back would include appropriate data from a
database, obtained using ADO code.
ActiveX Data Objects (ADO) is a collection of
software components providing a programmatic

268
interface to access the data sources from client
applications. ADO acts as a layer to access any data
store in a generic way from the application code. It
eliminates the need to possess the knowledge of
database implementation and reduces the complexity
of dealing with the low level code needed to handle
the data.

Released in 1996, ActiveX data object (ADO)


originated from the concept of RDO (remote data
object) and DAO (data access object). One of the
constituents of MDAC (Microsoft data access
components), ADO and other MDAC constituents
provides a framework of components used by client
applications to access SQL, semi-structured and
legacy data stores.
ADO uses an OLEDB provider for connecting to the
data sources and accessing data. OLEDB is a
component based programmatic interface provided to
interact with different data sources. These data sources
can be both relational and non-relational databases
such as object databases, web pages, spreadsheets or e-
mail messages. Prior to OLEDB and ADO, ODBC
(open database connectivity) was the popular model
used in applications across platforms.
Accessing ADO with Visual Basic
Visual Basic is probably the most popular language in
which to develop applications for ADO. It is also the
language used in the examples and source code in this
chapter. Visual Basic is a very easy language to

269
understand and excellent for both beginners and
advanced developers.

Referencing ActiveX Data Objects


To write an application in Visual Basic using ActiveX
Data Objects, you must first tell Visual Basic about
them by adding ADO to the list of references that
Visual Basic uses to run an application. You may do
this by selecting the Project -> References menu item
so that the References dialog box appears as shown
below. In the Available References list box, select the
latest version of Microsoft ActiveX Data Objects
Library that you have installed. Now you are ready to
create and use ADO objects within your current Visual
Basic application.

270
When redistributing ADO applications, you should use
MDAC redistributable package available for download
from Microsoft‘s website.

10.2 CREATING ACTIVEX DATA OBJECTS

In Visual Basic, you can create new ADO objects by


simply referencing the ADODB classes of the
Microsoft ActiveX Data Objects Library. The
following piece of code creates a Connection and a
Recordset object in Visual Basic:
‘create a reference to a Connection object

271
Dim con As [Link]

‘create a reference to a Recordset object


Dim rst As [Link]

As with any other Visual Basic objects, you must


instantiate them before they can be used , as in the
following examples:
‘create a new instance of the Connection object
Set con =New [Link]

‘create a new instance of the Recordset object


Set rst =New [Link]

In the previous examples, the ADODB prefix to the


ADO objects is used in case your Visual Basic
development environment references another object of
the same class name in a different class library. The
following code illustrates how a DAO Recordset and
an ADO Recordset can be created in the same project:

‘which object model is this from?


Dim rst As Recordset

‘explicitly specifying the Data Access Object Model


Dim rstDAO As [Link]

‘explicitly specifying the ActiveX Data Object Model


Dim rstADO As [Link]

272
If you know for a fact that no other class library listed
in the References dialog box of your current Visual
Basic application has the same class name as ADO,
you may remove the ADODB prefix when declaring
and instantiating object variables. However, if you are
using more than one object model with the same class
definitions, not specifying the library that comes first
in the list of references to the project.

In Visual Basic, it is always a good idea to remove an


object from memory once it is no longer being used. It
is done by setting the object to Nothing , as follows:

‘remove the objects


Set con =Nothing
Set rst =Nothing

10.2.1 USING ADO WITH VISUAL BASIC: AN


EXAMPLE

To visualize how to work with ADO objects in Visual


Basic, the below example uses ADO to open a
connection to the Jet Biblio database and to return a
recordset containing the names of its first ten authors.
Each record is then written to a list box before both the
Connection and Recordset objects are closed. This
example makes use of dynamic control creation
supported by Visual Basic 6.0 or later; if you have an
earlier version, simply delete the code that defines,
instantiates, sets the properties of the list box, and

273
place a list box named 1stAuthor on the form at design
time.

To begin, create a new Application EXE project, and


open the Project ->References menu so that you can
see the Reference dialog box shown below. Select the
latest version of the Microsoft ActiveX Data Object
that you have installed, and press the OK button.

Now, replace the existing source code for Form1 with


the code shown in the given example and run the
application. That is it. Make sure that you have a
[Link] database located at C:\
Program Files\Microsoft Visual Studio\VB98, or if
you have it in another location, simply change the path
in the code that points to the Access database.

A Simple Visual Basic Example.


Option Explicit
Private WithEvents lstAuthors As ListBox
Private Sub Form_Load()
‘ create new instances of the Connection and
Recordset objects
Dim con As [Link]
Dim rst As [Link]
‘ instantiate the Connection and Recordset objects
Set con = New [Link]
Set rst = New [Link]

274
‘ create two strings to define the connection and the
recordset
Dim sConString As String
Dim sSQL String As String
‘ Create list box control
Set lstAuthors =[Link](“[Link]”,
_“lstAuthors”, _ Me)
[Link] = True

‘ open the BiblioDSN data source with the Connection


object
sConString = “Provider = [Link].4.0;
* _ & “Data Source =C:\ Program Files”_ & ”
\Miocrosoft Visual Studio”_ & ”\VB98\[Link]”
[Link] sConString
[Link] “ Connection opened.”
‘create a Recordset object from a SQL string
sSQLString =”SELECT TOP 10 Author “ & _
“FROM Authors”
Set rst =[Link](sSQLString)
[Link] “SQL statement processed.”

Do Until ([Link])
[Link] rst(“Author”).Value
[Link]
Loop
[Link] “Getting data now...”

Do Until ([Link])
[Link] rst (“Author”).Value

275
[Link]
Loop
[Link] “End of data.”
‘ Close and remove the Recordset object from memory
[Link]
Set con =Nothing
[Link] “Closed and removed ” _ & “Recordset
object from memory.”
‘close and remove the Connection object from
memory.”
[Link]
Set con= Nothing
[Link] “Closed and removed” _ & “Connection
object from memory.”
End Sub
Private Sub Form_Resize()
‘ this code is added for asthetics
[Link] =0
[Link] =0
[Link] =[Link]
[Link] =[Link]
End Sub

The important technique to notice from this example is


how the ADO objects are created in the beginning of
the code example, and how the ADO objects are
removed at the end of the code example.

10.3 ESTABLISHING A REFERENCE

276
Referencing the Type Library

ActiveX components can contain numerous classes,


each with one or more programming interfaces. These
interfaces can have methods and properties. The
components can also have many enumeration
constants which are symbolic names for constants that
are passed or returned over the interface. For name
scoping and management, each application defines its
own group of these definitions into a type library. The
type library is used by programming languages to
check the correctness of calls to the component and it
is used by COM when it creates the data packet which
conveys a method call from one Windows process to
another. (This data packet creation is called
marshalling.)

You must reference at least two type libraries to access


IOM servers. One is for base SAS software and the
other is for the Workspace Manager. These type
libraries get installed when you install the SAS System
as a whole or when you install the SAS Integration
Technologies client. However, before you can write
Visual Basic code to call the base SAS IOM
interfaces, you must reference these type libraries from
within your Visual Basic project.

To reference these type libraries from Visual Basic:

277
1. From the Visual Basic Menu Bar, find the
References menu item. Depending on the version of
Visual Basic that you are running, this is either under
the Project (VB6) or under the Tools (VBA) menu.

2. Select this menu item to bring up the references


dialog. This dialog lists every registered type library
on the System. This list is divided into two groups.
The type libraries which are already referenced by the
project are listed first. All the remaining registered
system type library are listed after that in alphabetical
order. The first group shows the list that can be
referenced in your program. The second group helps
you find additional libraries to add to the first group.

3. Find the type library labeled "SAS: Integrated


Object Model (IOM)" and click the check box to add
the reference to your project. (Simply selecting the
line is not sufficient, you have to check the box.)

4. Similarly, find the type library labeled


"SASWorkspaceManager" and click its check box to
add this reference to your project.

5. Click OK to activate these changes.

After referencing these libraries, you can use them


immediately. Also, if you reopen the references dialog,

278
you will see that these libraries have been moved up to
the top of the list with the other referenced libraries.

Each type library has a name, known as the Library


Name, that is used in programming to qualify (or
scope) all names (such as components, methods,
constants, and so on) used within it. (This name is not
necessarily the same as the name of the file containing
the type library.) Visual Basic will look up the names
in your program by going through the referenced type
libraries in the order that they are listed in the
references dialog. If two type libraries contain the
same name, then Visual Basic will get its definition
from the first library in the list, unless the name is
qualified with a library name.

The base SAS IOM library name is "sas". You can use
this to qualify any identifier defined in that library. For
example, the base SAS library has a FormatService
component. If another library in your application has
its own identifier with the same name, then you would
reference the SAS component by using
[Link].

The Visual Basic Development Environment

After the type library is referenced, its definitions


become available to the Visual Basic Object Browser.
From the Visual Basic development environment, the

279
Object Browser is typically available via a toolbar
icon, a menu selection or the F2 key.

The Object Browser can show all referenced type


libraries at one time or can focus on any one of them.
To focus on the base SAS IOM library, select "SAS"
from the drop-down box in the upper left. The left
pane of the Object Browser will then show only the
component classes, interfaces and enumerations for
SAS components. If you select a component (such as
FileService) on the left, its methods and properties will
be shown on the right. When you select an item in the
right pane, more complete information (such as the
parameters to pass to a method and a brief description
of the method) are shown at the bottom.

Referencing a type library also activates Visual Basic


Intellisense ™ for all programming language names in
the library. As you begin to type a name like
[Link], you will see the Visual Basic editor
show you the list of possible names to complete your
typing. As you code a method call, Visual Basic will
show you each parameter that you need to provide.

For VB6 and later or Microsoft Office 2000 VBA or


later, the Object Browser and the Visual Basic editor
are connected to the Base IOM interface help file. In
the Object Browser, if you click on the "?" button or
press the F1 function key, you will see the help page

280
for the selected item. In the editor, if you press F1 with
your cursor on a name, you will get help for that name.

10.4 WORKING WITH OBJECT VARIABLES


AND CREATING A WORKSPACE

Your Visual Basic program’s interaction with the SAS


System begins by creating a [Link] object.
This object represents a session with the SAS System
and is functionally equivalent to a SAS Display
Manager session or the execution of base SAS
software in a batch job. Using a workspace from
Visual Basic requires that you declare an object
variable to reference it. An example declaration is:
Dim obWS as [Link]

Note that this statement only declares a variable to


reference a workspace. It does not create a workspace
or assign a workspace to the variable. For creating
workspaces, the SAS Integration Technologies Client
provides the Workspace Manager. The Workspace
Manager is an ActiveX component which can be used
to create SAS Workspaces, either locally or on any
server that runs the SAS Integration Technologies
product.

If the server is remote, you can create a workspace


using either the server's DNS name (such as
"[Link]") or a logical name (like

281
"FinanceDept") given to you by your system
administrator. Please see SAS Workspace Manager for
more information on creating workspaces on remote
servers.

If the SAS System is installed on your local PC and


you want to create a workspace that runs locally, it is
very easy to use the Workspace Manager to create the
workspace and assign it to your object variable. The
example below shows you how this is done:
Dim obWSMgr As New
[Link]
Dim obWS As [Link]
Dim errString As String
Set obWS =
[Link]("
My workspace", VisibilityNone, Nothing, "", "",
errString)

By using the keyword new, you instruct COM to


create a SAS Workspace Manager and assign a
reference to it when the object variable (obWSMgr in
this case) is first used.

After you create the instance of the Workspace


Manager, you can use it to create a workspace (SAS
session) on the local machine. The Workspace
Manager has a Workspaces collection which has a

282
CreateWorkspaceByServer method for creating a new
workspace.

The first parameter to this method is workspace name


of your choice. The name can be useful when your
program is creating several workspaces and must later
distinguish among them. The next parameter, the
visibility, can be used when you need to communicate
a workspace to another component. You seldom need
to do this except when working with ActiveX Data
Objects (ADO). The VisibilityNone value indicates
that the workspace will not be shared with other
components.

The next parameter is an object to identify the desired


server for the Workspace. Since we are creating a
workspace locally, we pass the Nothing (a Visual
Basic keyword) to indicate that there is no server
object. The next two strings are for a user ID and
password. Again, we don't need these to create a local
workspace. The final parameter is a string which can
return error information.

This method returns a reference to the newly created


workspace.

Note: Whenever you assign a reference to an object


variable, the assignment uses the Set keyword. If you
do not use Set, Visual Basic will try to find a default

283
property of the object variable and set that default
property. This is very different than assigning an
object reference to the variable itself.

You can prove that the above example program works


by instructing the server to print its Internet Domain
Name System (DNS) name. The following program
creates a SAS workspace on the local computer, then
prints the DNS name, and finally, closes the newly-
created workspace.
Dim obWSMgr As New
[Link]
Dim obWS As [Link]
Dim errString As String
Set obWS =
[Link]("
My workspace", VisibilityNone, Nothing, "", "",
errString)
[Link]
[Link]
[Link]

As you use other features of the SAS System, you will


need additional object variables to hold references to
objects created within your SAS Workspace. These are
declared similarly. For example, if you want to assign
SAS FILEREFs, then you may want an object variable

284
to reference your workspace’s FileService. The
declaration would be:

Dim obFS as [Link]

Such declarations never use the keyword new because


doing so asks COM to create the object. Object
variables for objects within the workspace will always
reference objects created by the Workspace, not COM.
In fact, when you use new in a declaration, you will
see that Intellisense provides a much shorter list of
possibilities because it lists only those classes of object
that COM knows how to create.

Then, to use the obFS variable to hold a reference to


the FileService for the workspace referenced by
obWS, the statement would be:
Set obFS = [Link]

Again, note that the assignment of an object variable


must use the Set keyword.

Basic Method Calls

285
After you create an object variable and set it with an
object reference, you can make calls against the object
and access the object’s properties.

The first example assigns a SAS Libref using the IOM


DataService.
' Create a workspace on the local machine using
the Workspace Manager
Dim obWSMgr As New
[Link]
Dim obWS As [Link]
Dim errString As String
Set obWS =
[Link]("
My workspace", VisibilityNone, Nothing, "", "",
errString)

' Get a reference to the Workspace's DataService.


Dim obDS as [Link]
Set obDS = [Link]

' Assign a Libref named "mysaslib" within the


new workspace
' (This is an example of a method call that returns
a value)
' Note: you must have a "c:\mysaslib" directory
for this to work
Dim obLibref as [Link]
Set obLibref = [Link]("mysaslib",
"", "c:\mysaslib", "")

286
' Should print "mysaslib"
[Link] [Link]

' Deassign the Libref. (An example of a method


call that does not return
' a value)
[Link] [Link]

' Close the Workspace. (Another example of a


method call that does not
' return a value.)
[Link]

This example illustrates three method calls and two


property accesses.

In Visual Basic, method calls that use a return value


are coded differently from those that do not. The
AssignLibref call returns a reference to a new Libref
object. Since the method returns a value and that value
is being used in this call, the method must be called
with parentheses around its arguments. The calls to
DeassignLibref and Close, on the other hand, do not
return a value. (Neither of these methods can return a
value.) Thus, no parentheses are used following the
method name. This is true even for DeassignLibref
which passes a parameter in the method call.

287
When passing parameters, you must first understand
whether the parameter is for input or output (also
known as ByVal and ByRef in Visual Basic).
Unfortunately, the Visual Basic Object Browser does
not provide this information. In many cases,
understanding the role of the parameters will make it
obvious. For example, the Libname string passed to
DeassignLibref is used by that method to know which
Libref to deassign but the method does not update the
parameter. Thus, it is an input parameter. If you are
not sure which type of parameter is required, then you
can consult the Help or documentation to find out.

Input parameters can be passed by a constant value


(such as mysaslib for a string parameter or 0 for a
numeric parameter) or an expression. They may also
be passed using a variable whose value is taken as
input to the method. This technique is used in the
DeassignLibref call in the example. Output parameters
require the use of variables that will be updated at the
time the call returns.

Understanding the data type of the parameter is just as


important as understanding the direction. The data
type is listed in the Object Browser. If the provided
constant, variable, or expression has the same type as
the parameter, then no conversion is necessary.
Otherwise, Visual Basic may try to convert the value.
If you do pass a different type than the method

288
actually defines for that parameter, make sure that you
understand Visual Basic’s data conversion rules.

The parameters in IOM methods have a range of data


types. Many are standard types such as String, Long,
Short, Boolean and Date. Others are object types
defined by a type library (such as [Link] in the
example above). Most parameters are designed to
accept or return a single type of object. In these cases,
it is best to use an object variable of that specific type.
It is possible, however, to use variables declared with
the generic object type Object. In some case, methods
may return more than one type of object, depending on
the situation. For example, the GetApplication method
for a SAS Workspace may return different types of
objects (based on the application name that was
requested). It is declared to return the generic object
type.

When a parameter can take some fixed set of integer


values, its declaration will use an enumeration defined
in the type library. For example, the
Fileref:OpenBinaryStream method takes a parameter
indicating the open mode of the stream. The type of
this parameter is [Link]. In the current
version of Visual Basic, you cannot declare a variable
of this type. You must use a Long instead. The
declaration is still important because it tells you the set
of possible values and provides a constant for each.

289
For example, if you want to open a stream for writing,
you would pass a constant of
[Link].

Some Visual Basic procedures and subroutines take


optional parameters. When calling such routines, you
often pass the parameters by specifying their name
(such as "color:="Red"). This feature of Visual Basic
is not used by SAS IOM methods because it does not
work naturally with other types of client programming
environments including Visual C++. Therefore, it is
best to simply list parameters in order without showing
their names.

Many objects have properties that can be easily


obtained simply by naming the property. Libref
objects, for example, have a Name property which is
used in the example above. Some properties are read-
only, but others can also be set. Such properties can be
set using a normal assignment statement. Keep in
mind, however, that if the property type is an object
type, then you will need to use Set with your
assignment statement (as described in the previous
section).

Because SAS servers will often be located on a


platform that is remote from the machine running your
Visual Basic program, much better performance is
achieved by keeping the number of function calls to a

290
minimum. This means that many IOM methods have a
large number of parameters and accept arrays for those
parameters. Visual Basic Intellisense technology is
very helpful for keeping track of parameters as your
code them. The next section describes how to pass
arrays in Visual Basic method calls.

Passing Arrays in IOM Method Calls

When the SAS System generates a listing, it may


contain thousands of lines. If the IOM calls to read the
listing returned only one line at a time, then many
thousands of calls would be needed to fetch all of the
output. In order to get better performance in situations
like this, IOM methods make heavy use of arrays.

By returning an array of lines, the FlushListLines()


method can potentially return all LIST output in one
call. Similar situations occur in many other places in
IOM including reading and writing files, getting and
setting options and listing SAS Librefs and Filerefs. It
is important, therefore, to understand when arrays are
being used and how to declare and pass them.

Visual Basic arrays can be fixed-size or dynamic. An


array dimensioned with a size is fixed size. An array
dimensioned with no size (empty parentheses) or

291
declared with the Redim statement is dynamic. For
array output parameters you must use dynamic array
variables because the size that SAS will return is not
known when the array variable is declared.

The following example lists all Librefs in the


workspace.
' Create a workspace on the local machine using
the Workspace Manager
Dim obWSMgr As New
[Link]
Dim obWS As [Link]
Dim errString As String
Set obWS =
[Link]("
My workspace", VisibilityNone, Nothing, "", "",
errString)

Dim obDS as [Link]


Dim vName as variant
' Declare a dynamic array of strings to hold
libnames
Dim arLibnames() as string
Set obDS = [Link]
' pass the dynamic array variable to "ListLibrefs".
Upon return,
' the array variable will be filled in with an array
of strings
' one element for each libref in the workspace
[Link] arLibnames

292
' Print each name in the returned array
For Each vName in arLibnames
[Link] vName
Next vName
' Print the size of the array
[Link] "Number of librefs was: " &
Ubound(arLibnames)+1
[Link]

In the object browser, you can tell that the ListLibrefs


names parameter is an array of strings because it is
shown as follows:
names() as string

The empty parenthesis indicate an array. A few of the


array parameters in IOM require a two-dimensional
array. The Object Browser does not distinguish the
number of dimension. You must consult the help or
documentation to determine this.

After the ListLibrefs call returns, there will be one


array element for each Libref assigned in the
Workspace. The For Each statement can be used to
iterate through these elements. You must use variant
as the type of the loop control variable.

In many cases, you will need to know the size of the


returned array. Visual Basic allows arrays to be
created with a particular lower and upper bound in

293
each dimension In order to allow better compatibility
with other client programming languages, all IOM
calls require that the lower bound be zero. Input arrays
will not be accepted if their lower bound is not zero.
Output arrays will always be returned with a lower
bound of zero.

The size of the array can be determined by checking


its upper bound. For a one dimensional array, you can
get the upper bound by passing the array name to the
Ubound function. Since the array is zero-based and
Ubound returns the number of the last element, you
must add one to get the size of the array.

You can get the Ubound for each dimension of a two


dimensional array by passing a dimension index. The
following example illustrates this technique:

Dim table()

Redim table(5,2) ' 6 rows (0 through 5) and 3 columns


(0 through 2)

[Link] "Number of rows: " & Ubound(table,


1)+1
[Link] "Number of columns: " & Ubound(table,
2)+1

294
When passing input arrays, you can pass a fixed size
array if you know the size in advance. The following
code provides an example:
' Create a workspace on the local machine using
the Workspace Manager
Dim obWSMgr As New
[Link]
Dim obWS As [Link]
Dim errString As String
Set obWS =
[Link]("
My workspace", VisibilityNone, Nothing, "", "",
errString)

Dim obLS as [Link]


' Declare a fixed size array of strings to hold input
statements
Dim arSrc(2) as string
' Declare a dynamic array of strings to hold the
list output
Dim arList() as string
' These arrays will return line types and carriage
control
Dim arCC() as long, arLT() as long
Dim vOutLine as variant
arSrc(0) = "data a; x=1; y=2;"
arSrc(1) = "proc print;"
arSrc(2) = "run;"
Set obLS = [Link]
[Link] arSrc

295
' Get up to 1000 lines of output
[Link] 1000, arCC, arLT, arList
' Print each name in the returned array
For Each vOutLine in arList
[Link] vOutLine
Next vOutLine
[Link]

The number of input statements is known in advance,


so the arSrc array variable can be declared as a fixed
size. (A dynamic array could also have been used.)

For some methods, you may sometimes want to pass


an input array with no elements. Unfortunately, Visual
Basic does not have syntax for creating either a fixed
size array or a dynamic array with zero elements.

To work around this deficiency in Visual Basic, IOM


methods allow you to pass an uninitialized dynamic
array variable. When you do this, it is the same as if
you had created an array with no elements.

Visual Basic does handle output arrays with no


elements properly. When an array has no elements, the
Ubound() function will return –1 and the For Each
statement will not execute the body of the loop.

296
Notes on Using Enumeration Types in Visual Basic
Programs

Older versions of Visual Basic (such as VBA in Office


97) do not support defining variables as enumeration
types. For these older versions, you have to define
them as type long. From the example above, consider
the statement:
Dim arCC() as long, arLT() as long

Here, the variables arCC and arLT are being used as


arrays of LanguageServiceCarriageControl and
LanguageServiceLineType, respectively. However,
since this program was written to execute in a Visual
Basic for Applications (MS Office 97) environment,
the variables are defined as arrays of long integers.

For newer versions (such as Visual Basic 6) you need


to use enumeration types. To execute this program in a
VB6 environment, the line would be changed to:
Dim arCC() as LanguageServiceCarriageControl
Dim arLT() as LanguageServiceLineType
Note that the enumeration constants themselves are
available for use in both environments. Given that
arCC and arLT are defined appropriately for the
environment, the following statements are valid in
both the old and new versions.
arCC(0) =
LanguageServiceCarriageControlNormal

297
arLT(0) = LanguageServiceLineTypeSource

Object Lifetime
You should use the [Link] method to close
a workspace when you are done with it. This will also
delete all objects within the workspace. For some
types of objects, such as streams, you can be done with
the object long before you are done with the
workspace. These objects typically have their own
Close method which removes the object and performs
other termination processing (such as closing the file
against which the stream is open). The lifetime of
objects that do not have a Close (or similar) method, is
managed by the Workspace in which the object is
created.

In Visual Basic, you can release the reference held by


an object variable by assigning the keyword Nothing
to that variable. The syntax is simply:
ObStream = Nothing

Using this technique, it is possible to make Visual


Basic release its references to an object. Doing so does
not, however, delete the object because the Workspace
still references the [Link] a special case, if your
program releases its references to all of the objects in a
SAS server, then the server will delete the workspace
and all of the objects in it. This behavior is
implemented to prevent excess SAS processes from

298
being left on a machine when clients fail to close their
workspaces properly. If a client program terminates
abruptly or is killed by the user from the Task
Manager, then COM notifies SAS of this at a later
time. In current versions of COM this takes about six
minutes.

Exceptions

Method calls sometimes fail. When they do, Visual


Basic raises an error condition. If you want to write
code that responds to error conditions, then you should
code On Error Goto Next after each call. If you want
to centralize the code that responds to error conditions,
then code an On Error Goto with a label and place
your error handling code at the label.

When an error occurs, COM and Visual Basic store


the error in the err predefined variable of the type
[Link]. The two most important fields in this
variables are [Link] and [Link].
[Link] can be used by your program logic to
determine what kind of error occurred.

[Link] provides a text description of the


error. It can also provide important details about the
error. For example, in the case of an error in opening a
file, the description will provide the name of the file
that could not be opened.

299
Different errors are assigned different codes. IOM
method calls can return many different codes. The
code that they return are listed in various enumerations
whose names end in "Errors". For example, the IOM
DataService defines an enumeration called
DataServiceERRORS in which the constants for all of
the possible errors returned by the DataService are
defined. The documentation and on-line help show the
errors that a particular call is most likely to raise. In
addition to those listed explicitly for the method,
[Link] is always possible.

Receiving Events

Some IOM objects can generate events. For example,


The LanguageService generates the events
DatastepStart, DatastepComplete, ProcStart,
ProcComplete, SubmitComplete and StepError. In the
Object Browser, you can recognize objects that
generate events because the event procedures are
marked using a lightning bolt icon.

Your Visual Basic program can implement procedures


which receive these events if you declare the interface
using the WithEvents keyword.
Dim WithEvents obLS As [Link]
This declaration must be outside any procedure.
Once you have done this, the Visual Basic
development environment will provide empty

300
definitions for the event procedures. The following
code segment is a definition that is provided for the
ProcStart event, along with a line that has been added
to print a debug message tracing the start of the
procedure.
Private Sub obLS_ProcStart(ByVal Procname As
String)
[Link] "Starting PROC: " & Procname
End Sub

Note that the event procedure name is of the form


Object_Event.

In your routine which initializes your workspace


variable, you should initialize the LanguageService
variable using a statement such as:

set obLS = [Link]


Once this initialization has occurred, your events
procedures will be called whenever the SAS System
fires an event.

[Link] AND DATA REPORTS


Before you create a custom report, you should
consider who you want on your report, what
information you want on the report, and how the
report will look. Proper planning before you start
designing your report will save you time, and help
avoid mistakes. It is even a good idea to draw the

301
report on paper first to make sure your design is
clear.

Step WHO? WHAT? HOW?


What What How do
Need records fields do you want
to do you you want the
know want to on the report to
include? report? look?

Crystal
Mod- Reports
Query Export for
ule
Blackbaud

You must have a group of records and an export file


before you create a new report, but it is not always
necessary to create a new query and export every
time. For example, you want to create a report of your
trustees’ home and business phone numbers. You
already have a query of your current trustees, so you
do not need to generate a new one for this report.

302
11.1 CREATING AN EXPORT FILE
Before you design and create your report, you need
to decide what kind of information you want to
display. What fields do you need from The Raiser’s
Edge to generate the correct data on your report?
Creating the export file is the first and most
important step. Without the correct fields in your
export, you will not be able to produce the results
you want on your report.

When selecting the fields you need from The Raiser’s


Edge, always include any field you are undecided
about. You do not have to include it in the report if
you decide it is unnecessary, but once you are in
Crystal, only fields you exported are available. If you
decide you need another field, you will have to export
your data again.

Creating a new export file

303
Based on your Trustee query, create an export file with
the fields Name, Home Phone, and Business Phone.
Your Director of Development wants a list of all the
current trustees and their home and business phone
numbers, if available. Use your Trustee query to
create an export file with fields Name, Home Phone,
and Business Phone. Design a custom Crystal report
displaying the trustee names in alphabetic order, with
a grand total at the bottom.

1. On the Raiser’s Edge bar, click Export. The


Export page appear

[Link] the action bar, click New Export. The Create a


New Export screen appears.
3. In the What type of export do you want to create
box, select “Constituent” because you want to gather
your trustee records.

304
4. In the Export format field, select “Blackbaud Report
Writer Database (MDB)”. Selecting an .MDB file type
tells the program to format the data in a way Crystal
Report.

4 i). Create New Export. By selecting the New

Constituent option as shown above.

305
Choose the appropriate Export format as Blackbaud
Report Writer Database (MDB).

5. Click Create Now. The New Constituent Export


screen appears.
6. On the General tab, click Include to select the
specific records to include in the export.

7. Because you want to export only your trustees’


records.
[Link] you want to export information about your
trustees, enter “trustee” in the Query name field.
Click Find Now and any query beginning with
“trustee” displays.

306
9. Highlight the Trustees query.

10. Click Open and you return to the General tab.


“Trustees” appears to the right of the Include button.

[Link] the defaults for all other fields on the


General tab.

12. Select the Output tab.

307
Home Phone, and Business Phone in your export,
you must select those fields from the tree view on the
left.
13. From the tree view on the left, in the Available
Fields to Export frame, click the plus sign next to
Biographical.
[Link] fields are in alphabetical order. Scroll down the
list and highlight Name. To move Name into the
Output box, click Select at the bottom of the screen.

308
309
15. Because you want to include Constituent Export
from the tree view on the left, in the Available Fields
to Export frame, scroll down the list and click the
plus sign next to Address. Then, click the plus sign
next to Preferred Address.

[Link] scrolling down the list under Preferred


Address, and click the plus sign next to Phones.
Highlight Phone number.

310
[Link] Select at the bottom of the screen. The
Phones screen appears.

[Link] the default of All Phones. Click OK.

[Link], Preferred Address, Phones, Phone


number appears in the Output box on the right.

20. From the tree view on the left, in the Available


Fields to Export frame, click the plus sign next to
Primary Business information. Then scroll down
and click the plus sign next to Address, and then
Phones

311
.

312
21. Under Phones, highlight Phone number and
click Select. The Phones screen appears.

22. Accept the default of All Phones. Click OK.

[Link] Business information, Address, Phones,


Phone number appears in the Output box on the right.

313
24. This completes the selections for the export. Click
Export Now in the lower right corner.

25. The Export file name screen appears. Name your


export “Trustee Phone List”, and select a location to
save your export. The Save as type field should
automatically show “Blackbaud Report Writer
Database (MDB)”.

It is important to remember the location of your .mdb


database file. When you begin creating your Crystal
report, you will be prompted to locate [Link] file.

314
[Link] Save and the export processes. A screen
appears telling you the number of constituent
records exported.

[Link] OK.
[Link] the “X” in the top right corner of the
New Constituent Export screen. A message
appears, asking if you want to save the export.
[Link] Yes and name the export “Trustee Phone
List”.

315
[Link] Save. You return to the main Export page.

11.2 CREATING A REPORT -


CRYSTAL REPORTS FOR
BLACKBAUD
After you create your Trustee export file with the
fields you need, you are ready to start designing your
report.

Report Setup
To create a new custom report in Crystal Reports, you
need to open a new blank report and attach the export
file you created to serveas the data. Once you start
building your report, only data generated in the export
file is available. You are not connected to your
Raiser’s Edge database.
Creating a new custom report
Now that you have created your export, you are ready
to start creating your new custom report and
formatting your report to create the look you want.

1. From your desktop, go to Start, Programs,


Crystal Report for Blackbaud . You may also
have an icon on your desktop you can double
–click to launch the program.
2. Crystal opens and the Welcome to Crystal
Reports for Blackbaud screen appears.

316
In the Create a New Crystal Report Document frame,
select As a Blank Report. The blank form is shown in
the following page.
3. 3. In the Create a New Crystal Report Document
frame, select As a Blank Report.
4. Click OK. The Data Explorer screen appears

317
[Link] the plus beside Database Files to expand the
tree view.

[Link] Find Database File, and click Add. The


Open screen appears so you can find your Raiser’s
Edge database file.

[Link] the .mdb file you need, and click Open.

318
You return to the Data Explorer screen. Notice all
your database fields are listed in the tree view.

8. Highlight all the exported fields from The Raiser’s


[Link] select all the fields at the sametime, highlight
the first field with your mouse, click the last field in
the list. All the fields in between highlight
automatically.
9. Click Add. The fields appear with green ticks to
indicate they have been included for your Crystal
report. When you select the export Blackbaud Report
Writer Database (MDB) in Export, linking tables are
included in The data file (in addition to the fields you
select). Typically, you may not use this data in your
Crystal report. However, it is best to select all the data
for your report in these beginning steps. By doing this,

319
you avoid repeating steps if you leave intended fields
for your report behind.

320
10. Click Close. A blank Crystal report opens, with the
Vis ual Linking Expert screen on top.

The Visual Linking Expert screen shows the tables in


the export file, and how they link together. For most
reports, you do not need to alter these tables or their
links manually. When you click OK, Crystal Reports
automatically links the tables correctly.

11. When you click OK. A blank Crystal report is now

321
available, along with the Field Explorer box. This
box contains all the fields you exported from The
Raiser’s Edge. You will use these fields to build your
report.

11.3 REPORT SECTIONS

On a new Crystal report, five standard sections


designate how and where information displays on a
report. Additional sections are added when groups and
totals are established. As you build your report, it is
very important to make sure you insert the correct

322
fields into the correct sections. For example, any field
you want the program to calculate, like Gift Amount,
must be inserted into the Details section.
Report Header. Information in this section appears
at the top of the first page of the report.

Page Header. Information in this section appears at


the top of each page of the report.

Details. Information in this section represents the


results of the report. It is where the majority of the
creation takes place, and it is responsible for the bulk
of the data you see when you look at the report. If the
Details section occupies one line in the Design
window, each constituent is allotted one line on the
report.

Report Footer. Information in this section of the


report appears at the bottom of the last page of the
report. For example, you insert your grand total or
summary data here.

Page Footer. Information in this section appears at


the bottom of each page of the report. This is a good
place for page numbers or running totals.

Creating a Phone List

Generating a phone list is an easy way to get familiar


with Crystal Reports and learn some of the basics. In

323
this report, you are working with a limited number of
fields, and you do not need to write any equations or
formulas. As you begin to insert fields onto the report,
do not be afraid to make a mistake. Because you are
working only with an export file, it is not possible to
damage your database in any way. The Raiser’s Edge
and Crystal Reports are completely separate programs.

Report Layout

The placement of the fields on the report determines


the final look and effectiveness of the report. It is
important to understand that fields are calculated and
grouped based on the section into which you insert
them.

Inserting fields into a new report

Once you design your report, you are ready to start


inserting your export fields into the report. Pay close
attention to the fields and report sections to make sure
you place everything correctly.

1. From the new blank report, in the Field


Explorer box, click the plus sign next to Database
Fields. All the data from The Raiser’s Edge appears.

324
Remember that links and identifier keys are exported
out of The Raiser’s Edge along with the fields and
data. When you look through the Field Explorer
box, make sure you insert fields onto the report, not
LINKs or IDKEYs.

2. Click the plus sign next to CnBio.

325
[Link] on your report design, the first field you need
to insert is constituent name. Highlight CnBio_Name.

[Link] and drag it up to the far left side of the Details


section. Release your mouse to drop the field in place.

The field name is automatically added in the Page


Header section above the field.

326
Before you add any other fields, you may need to
move or size this field to make sure it is the correct
size for the data. If the box is too small, the data will
be truncated. If the box is too large, there will be too
much blank space between field.
Sizing fields in a report
If you notice the standard length or height of a field is
too big, or not big enough to display your information
correctly, you can change the size of the field after it is
on the report.
[Link] change the length of a field, click the field once
to highlight it. Move your cursor over the small black

327
square on the right side of the highlighted rectangle
until it changes to a double arrow.
2. Maintaining the double arrow, click and drag the
rectangle to the left to shorten the field size, or to the
right to lengthen the field. For this report, shorten the
constituent name field and the attached header field to
approximately two inches.

You can resize the fields at any time.

328
Moving fields in a report
After you insert your fields into the report, you may
need to move them to get the result you want.

1. To move a field after you place it on the report,


click the field once to highlight it, then drag it to the
new location. To save time, you can size more than
one field simultaneously. For example, if you need to
size constituent name and the field header, click
CnBio_Name in the Details section. While holding
down the CTRL key on your keyboard, click
CnBio_Name in the Page Header section.

When you select multiple fields, be careful not


to drag the first field you select on top of the second
field. This is an easy mistake to make once you press
the CTRL key. Make sure you click each field only
once. Wait until they are all highlighted. Now, you are
ready to move.
You can move fields left and right in the same
section, or up and down across sections, with the
exception of grand totals, subtotals, and summaries.
You can move fields left and right in the same
section, or up and down across sections, with the
exception of grand totals, subtotals, and summaries.
To save time, you can move more than one field
simultaneously. For example, if you need to move
constituent name and the field header together,
click CnBio_Name in the Details section. Then,
while holding down the CTRL key on your

329
keyboard, click CnBio_Name in the Page Head
section.
2. Once both fields are highlighted, click your cursor
in one of the boxes and drag the fields together to the
new location.

11.4 INSERTING ADDITIONAL FIELDS INTO A


NEW REPORT

Now that you are familiar with placing, moving, and


sizing fields on a report, you are ready to insert any
additional fields to complete your report. Insert the
home phone and business phone into the Details
section next to the constituent name.

1. On your report, click the plus sign next to


CnAdrPrfPh_1 in the Field.

2. In the text box, enter “Trustee Phone List”, then click


once outside the box, or press the ESC key on your
keyboard.

3. To centre the title across the top of the report, click


once on the field to activate the move box. Using the
small, black squares on either side of the box, stretch the
field all the way to the left of the Report Header section,
and then all the way to the right. The title box should
stretch across the entire length of the section.

330
4. On the toolbar, click the Align Centre button. The
title moves to the centre of the report.

11.5 SAVING A CRYSTAL REPORT

You can save your report with the data included, or


choose to save only the report layout. Once you save a
report layout, you can use the report over and over
with different sets of constituent data. Make sure you
name your report something you will recognise later,
and save it in a directory you create especially for your
Crystal reports.

331
Saving a report
Before you save your report, decide whether you want
to save it with your data attached or save only the
report layout.

[Link] save your report with the data, select to File,


Save Data with Report from the menu bar. If you
want to save only the report layout, do not check this
option.
2. On toolbar, Click save, the save as screen appears.
[Link] the File name field, enter the name of your
report. Name your report something you can
remember (for example, Trustee Phone List).
[Link] sure “Crystal Reports for Blackbaud” is in the
Save as type field.
[Link] Save.
[Link] close your report, click the “X” in the top right
corner.

11.6 DATA REPORTS


Data Report Designer allows you to create reports.
The reports generated through the Data Report
Designer take data from data sources such as Data
Environment. Using Data Report Designer you can do
the following:
• Export report to HTML file or text file.
• Create report with groups and aggregates.
• Create a hierarchical report
Components of Data Report Designer
The following are the various parts of Data Report

332
Designer.
Data Report object
This is like a Visual Basic form. It contains the
visible designer and code. Code is used to control
report at runtime by responding to the events
generated by the data report. Visible designer
allows you to design the layout of the report.
Sections Collection
This is collection of section objects. A section
object represents a section of the report. You can
use section objects at runtime to reconfigure the
section. At design time each section is represented
by a header, which is used to select the section.
Data Report Controls
Data report can contain only a set of special
controls. When you are in Data Report Designer,
a different toolbox is displayed with controls that
are specific to Data Report.

333

You might also like