Sei sulla pagina 1di 369

Visual Basic-6

Course Contents

1. Introduction to IDE and creating a Sample Application[13]


2. Projects using Intrinsic and Professional ActiveX Controls(1)[17]
3. Projects using Intrinsic and Professional ActiveX Controls(2)[19]
4. Projects using Intrinsic and Professional ActiveX Controls(3)[15]
5. Projects using Intrinsic and Professional ActiveX Controls(4)[13]
6. Menu Driven and Calculator Projects[12]
7. Projects involving Animation[9]
8. Projects using Multiple Forms[10]
9. Creation of User Defined ActiveX Control[21]
10. Project using ActiveX DLL[8]
11. Creating ActiveX Documents[16]
12. Database Projects(1)[14]
13. Database Projects(2)[13]
14. Database Projects(3)[17]
15. Database Projects(4)[21]
16. Database Projects(5)[16]
17. Crystal Reports[32]
18. Visual Basic Syntax[38]
19. . Classes and Objects[24]
20. Databases and Data Access objects[42]
21. Miscellaneous Projects[12]

x---------------------x

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Visual Basic-6
1. Introduction to IDE and Creating a Sample Project

Why Visual Basic-6:

Visual Basic-6 has emerged as one of the standard Windows Programming Language
and it has become a must for all Software people for developing Applications in Visual
Environment. So it is, one must learn Visual Basic-6.

What is our Objective in this Courseware?

The Overall Objective in this Courseware is to give a Hands-on Approach to develop


different projects in Visual Basic-6.0 using intrinsic, professional and user–created
ActiveX controls and also develop projects using databases, DAO’s, ADO’s, DLL’s,
Documents, Crystal Reports etc. covering almost all the essential features of VB-6

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Professional Edition. After reading one lesson any interested reader will be able to get
complete hands-on experience with the VB project and get a sense of fulfilment and
achievement. Learning by doing is the motto with which this courseware is written.
After giving a short introduction about VB-6 we will explain how to create and execute a
project in VB using some intrinsic ActiveX controls. Creating and executing projects
will be the central theme of all the lessons which we will be giving in this courseware.

What is Visual Basic-6?

Visual Basic-6 has its origin in Basic which was developed round about the year
1960, when high level languages were just being introduced to the computer community.
Microsoft has made it extremely powerful by gearing all its good features to the
Windows environment. Starting with the version 3 and then with 4, and then with 6,
Visual Basic is now at version 6. Basic is a Procedure Oriented Language intended to
implement single tasks in text based environment whereas Visual Basic is an Event
Driven Language intended to implement Projects or Applications containing multiple
tasks in Windows Environment.

What can Visual Basic do for you?

Visual Basic can serve as an ideal front end tool for the clients to interact. It has got
connectivity mechanisms for all types of databases situated far and wide in a network and
so it can cater to the needs of a large body of clients. Using the latest ActiveX
technologies, it can integrate the functionalities provided by other applications like Word
Excel and other Windows. Its internet capabilities provide easy access to documents and
applications across the internet. Above all it embodies the Object Oriented Technology,
which is the cutting edge technology for all the present day developments in the Software
World. The final application is a true EXE file and so can be freely distributed.

Structure of VB-6 Projects:

We said earlier that VB-6 implements projects or applications. A project is


developed using one or more Forms. A Form is simply a window containing one or
more Controls. Controls in VB consist of labels, text boxes, list boxes, combo boxes,
scroll bars etc. which are the constituents of windows environment. It is only the controls
that give VB, its immense power and so there is a lot of interest in creating more and
more powerful controls. ActiveX controls mark a significant development in controls
technology. In fact all controls in VB-6 are ActiveX controls, which have the extension
.ocx. These controls have properties whose values can be initialized at design time and
also varied during run time. The properties are something like variables. The controls
are activated by codes written in a high level language. By associating our problem
variables with the properties of the controls, our problem variables can be manipulated to
give the problem solution. In summary we can say that a VB project is made of forms,
controls and their properties and codes.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Integrated Development Environment:

The working environment in VB is often referred to as the Integrated Development


Environment or IDE, because it integrates many different functions such as design,
editing, compiling and debugging within a common environment. Since all our
projects are developed only in the IDE, let us now have a brief look at its features.
You will be able to understand their uses at the time of building projects. The VB IDE
looks as shown in the figure 1.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 1

Elements of Visual Basic IDE:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The VB IDE consists of the following elements.

• 1. Menu Bar
• 2. Context Menus
• 3. Toolbars
• 4. Toolbox
• 5. Project Explorer Window
• 6. Properties Window
• 7. Object Browser
• 8. Form Designer
• 9. Code Editor Window
• 10. Form Layout Window
• 11. Immediate, Locals and Watch Windows.

Menu Bar:

Menu Bar displays the commands you use to work with Visual Basic and is located at
the top. Besides the standard File, Edit, View, Windows and Help menus, menus are
provided to access functions specific to programming such as Project, Format or Debug.

Context Menus:

Context Menus provide certain short cuts to frequently performed actions. To open a
context menu, click the right mouse button on the object you are using. The specific list
of shortcuts available from context menus depends on the part of the environment where
you click the right mouse button. For example, the context menu displayed when you
right click on the Toolbox lets you display the components dialog box, hide the Toolbox,
dock or undock the Toolbox, or add a custom tab to the Toolbox etc.

Toolbars:

Toolbars provide quick access to commonly used commands in the programming


environment and is located below the menu bar. You click a button on the toolbar once
to carry out the action represented by that button. By default, the Standard toolbar is
displayed when you start VB. Additional toolbars, for editing, form design, and
debugging can be toggled on or off from the Toolbars command on the View Menu.
Toolbars can be docked beneath the menu bar or can “float” if you select the vertical bar
on the left edge and drag it away from the menu bar.

Toolbox:

Toolbox provides a set of controls that you use at design time to place them on the
form and is located on the left side. In addition to the default controls layout, you can
create your own custom layouts by selecting Add Tab from the context menu and adding
controls to the resulting tab.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Project Explorer Window:

The Project Window lists the forms, and modules in your current project. To
recapitulate, a project is simply a collection of files you use to build your application.

Properties Window:

Properties Window displays the different properties of the different objects, such as
size, caption, color etc., which can be set at the design time and located at the right side.

Object Browser:

The Object browser lists the available objects in your project, and gives you a way to
navigate through your code. You can use the Object browser to explore objects in VB ,
see what methods and properties are available for those objects, and paste code
procedures into your application.

Form Designer:

The Form serves as the designer window or the container for placing the different
controls, graphics and pictures needed for your applications and is located at the center.
There can be more than one form or a designer window for a single application.

Code Editor Window:

Every form has its own code editor window, where you write the codes for
manipulating the objects in the designer window.

Form Layout Window:

The Form Layout Window allows you to position the forms in your application using
a small graphical representation of the screen.

Immediate Window:

The Immediate Window is provided for debugging purposes and is located below the
form window. You can use it in the calculator mode to immediately compute big
expressions.

Visual Basic provides a great deal of flexibility, allowing you to configure the
working environment to best suit your individual style. You can choose between a
single or multiple document interface, and you can adjust the size and positioning of
the various Integrated Development Environment (IDE) elements. Your layout will
persist between sessions of Visual Basic.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


SDI or MDI Interface
Two different styles are available for the Visual Basic IDE: single document
interface (SDI) or multiple document interface (MDI). With the SDI option, all of the
IDE windows are free to be moved anywhere on screen; as long as Visual Basic is the
current application, they will remain on top of any other applications. With the MDI
option, all of the IDE windows are contained within a single resizable parent window.
To switch between SDI and MDI modes
1. Select Options from the Tools menu.
The Options dialog box is displayed.
2. Select the Advanced tab.
3. Check or uncheck the SDI Development Environment check box.
The IDE will start in the selected mode the next time you start Visual Basic.
– or –
Run Visual Basic from the command line with a /sdi or /mdi parameter.

Docking Windows
Many of the windows in the IDE can be docked, or connected, to each other or to
the edge of the screen. These include the Toolbox, Form Layout Window, Project
Explorer, Properties window, Color Palette, and Immediate, Locals, and Watch
windows.
With the MDI option, windows can be docked to any side of the parent window;
with SDI they can only be docked beneath the menu bar. Docking capabilities can be
toggled on or off for a given window by selecting the appropriate check box on the
Docking tab of the Options dialog box, available from the Options command on the
Tools menu.
To dock or undock a window
1. Select the window you wish to dock or undock.
2. Drag the window to the desired location by holding down the left mouse button.
The outline of the window will be displayed as you drag.
3. Release the mouse button.

Creating an Application or a Project:

Let us now wet our hands by actually creating an application using the IDE. Creating
any VB application consists of only three steps.

• 1. Create the interface by placing the required controls in the form window.
• 2. Set Properties to the controls using the Properties window of each control.
• 3. Write codes to manipulate the properties of the controls in the Code Window.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


You start VB by clicking the start button on the task bar. The screen displays the
programs list
as shown in the figure 2.

Figure 2

Now click on the items Visual Studio and then Visual Basic 6. You will get the
opening
Screen as shown in the figure 1.

Controls used in this Project:

We use five command buttons and one text box in this project. For drawing a control
in the form window, double click on the appropriate control. The control with default
characteristics is brought into the form. It can be dragged and resized according to your

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


requirements. Drag the above mentioned 6 controls from the Toolbox and position them
as shown in the figure 3. Of course you can size and position them according to your
liking.

Setting the Properties of the Controls:

Each control has a separate Properties window. The Properties window will be
normally visible on the right side. If it is not visible it can be opened by clicking
‘Properties Window’ from the View menu after selecting the required control. We can
initialize the properties like size, caption, color etc. by selecting the desired values using
the drop-down menu for the controls as well as the properties. The Text property of the
text box is given blank. We simply retain the names of the other controls as they are.
The form window with the five controls will be as shown in the figure 3.

Figure 3

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Functionalities required for the different Controls:

Let us assume that on clicking the first button, a message box should be displayed.
On clicking the second button a rectangle filled with yellow color should appear. On
clicking the third button a welcome message should appear in the text box. On clicking
the fourth button the welcome message should be erased.

Writing Codes for the Controls:

The code window is opened by double clicking the concerned control. The header
line and the ending line of the relevant function will automatically appear on the code
window. You have to enter only the body for the function. For referring to a property,
the usual dot notation used in OOP is used. For example the Text property of a text box
named Text1 is referred to as Text1.Text. In a similar fashion methods can also be
referenced. The codes for all the controls will be on the same window and the final
code window will look as shown in the figure 3a.

Private Sub Command1_Click()


'display message box
MsgBox ("this is a sample message")
End Sub

Private Sub Command2_Click()


ScaleMode = 3
Line (100, 10)-(300, 150), RGB(255, 255, 0), BF
End Sub

Private Sub Command3_Click()


Text1.Text = "welcome to VB6"
End Sub

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Private Sub Command4_Click()
Text1.Text = ""
End Sub

Private Sub Command5_Click()


End
End Sub

Figure 3a

Saving the Project:

When a project is saved for the first time it is done in two steps. When you select
‘Save Project as’ from the File menu, you will get the first dialog box which asks you to
save the form file with .frm extension. On saving the form file another dialog box
appears asking you to save the Project file itself. We can give appropriate names to the
form and the project, but in this case we retain the default names form1 and project1.
The project is now saved as project1.vbp and the form file is stored as form1.frm. When
you want to save the project after any subsequent editing, it is enough if you click ‘Save
Project’. Both the form and the project are saved by this single Save command.

Running the Project:

For running the project click Run->Start. The output window appears with all the
controls. This window represents the Run mode. Click the buttons one by one and
check the outputs obtained. A typical output is shown in the figure 4.

Closing and Reopening the Project:

For Closing the project click on the closing button of the output window or click End
from the Run menu or the exit button in the output window. If you want to reopen the
project, click ‘open project’ from the File menu. Opening a project will open all the files
in the project.

Viewing the Project Explorer Window:

As we said earlier, when you develop an application, you work with a project to
manage all the different files that make up the application. In order to view the
constituents of the project, open the project explorer window by selecting the item
‘Project Explorer’ from the View Menu. The Project Explorer window for the above
application is also shown in the figure 3. This project uses only two files, one project
file(project1.vbp ) and one form file(form1.frm). But in general a Project
may consist of the following files.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


• 1. One Project File that keeps track of all the components(.vbp).
• 2. One file for each form(.frm).
• 3. One binary data file for each form containing data for properties of controls
on the form(.frx). These files are not editable and are automatically generated
for any .frm file that contains binary properties, such as Picture or Icon.
• 4. Optionally, one file for each class module(.cls).
• 5. Optionally, one file for each standard module(.bas).
• 6. Optionally, one or more files containing ActiveX controls(.ocx).
• 7. Optionally a single resource file(.res).

Thus a project file is simply a list of all the files and objects associated with the
project, as well as information on the environment options you set. This information is
updated every time you save the project. All of the files and objects can be shared by
other projects as well.

Figure 4

Creating an EXE File:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


After completing all the files for a project, you can convert the project into an
executable file(.exe) by selecting ‘the make project.exe’ command from the file menu.
An EXE file can be executed outside VB environment and so can be freely distributed.

Summary:

In this lesson we have seen some features of the Visual Basic Integrated Development
Environment, and how to create an application, using the three elements, form, controls
and codes. It may be noted that any complex application will consist of only these three
elements, possibly using more forms, more controls with complex functionalities(pre-
defined as well as user defined) and some complex logic involving the properties of the
controls.
x-------------------------------------------------x

Visual Basic-6.
2. Projects Using Intrinsic and Professional ActiveX Controls(1)

Objective of this Lesson:

The objective of this lesson is to create the following projects illustrating the use of
Intrinsic and Professional ActiveX Controls.

• Creating Digital Clock using the Intrinsic Timer Control


• Creating Bar Chart using the Professional MS Barchart Control
• Creating Project using Combo Box

What is ActiveX?

ActiveX is a reusable and portable software component or control built according to


what are called COM(Component Object Model) specifications. It is the brainchild of
Microsoft. It is the practical realization of the philosophy, “write once use anywhere and
everywhere”. It provides a building block solution to complex problems. We have
already seen that VB-6 comes with certain intrinsic ActiveX controls which offer some
functionalities Such controls can be used not only in VB, but also in other ActiveX
compliant languages like VC++., VJ++, Delphi etc.

Can you Create Your own ActiveX Controls?

It is well known that any complex application is made of compatible combinations of


some basic functionalities. If you have predefined ActiveX controls to provide these
basic functionalities, VB-6 offers language support to package the basic controls to
another new single ActiveX control thereby providing an ActiveX solution to the

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


complex problem. In fact VB-6 has been developed essentially as a Control Creation
Language. Possibly you can visualize a scenario when every complex application will be
solved by a single user created aggregate ActiveX control.

Visual Basic ActiveX Controls:

When you start VB, the first window called the design window shows some 20
intrinsic controls like label, command button, option button etc., in the Toolbox. These
controls cannot be removed from the Toolbox. The Professional Edition of VB provides
some 34 more ActiveX controls which can be brought into the Tool box before using
them. These controls can be added to or removed from the Toolbox. In order to view
all the VB ActiveX controls select ‘New Project’ from the File Menu. You will get the
New Project Menu as shown in the figure 1. Click on the ‘VB Pro Edition Control’.
The Toolbox of the Design Window will now show the icons of all the ActiveX controls
as shown in the figure 2. When you move the mouse pointer over the icon, the names of
the controls will appear below them.

Figure 1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
Figure 2

Adding ActiveX Controls to the Toolbox:

In order to add one or more ActiveX controls to the Toolbox, select the item
‘Components’ from the Project menu. The Components Dialog Box will appear on the
screen as shown in the figure 3. Select the required control by clicking on the
rectangular box at the beginning. After selecting the required controls, click OK. The
icons of the selected controls will now appear on the Tool box and you can use them just
as you will use any other intrinsic ActiveX control.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 3

Functions of Some important ActiveX Controls:

We give below a list of some important ActiveX controls added in the Professional
Edition of VB-6. This is in addition to the intrinsic controls already introduced in earlier
versions.

• 1. The Common Dialog Control enables the users to create Dialog Boxes (open,
save, print, setup, font, help and so on) in their own applications.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


• 2. The Animation Control enables the users to play silent avi files producing
animation appropriate to the operations performed.

• 3. The Communication Control describes how to use it with a modem to dial a phone
number, interact with another modem or add advanced communication functionality
to your applications.

• 4. The Internet Transfer Control enables the users to transfer files to and from a
remote computer using TCP or FTP protocols.

• 5. The ListView Control enables the users to organize and view the data in
deifferent ways using the View Property.

• 6. The MAPI Control enables the users to sign-on to an electronic messaging


system, access an Inbox, send or receive messages or send file attachments.

• 7. The Masked -Edit Control enables the users to create mask platforms that prompt
them for date, time currency or customized data input.

• 8. The MSChart Control enables users to create barchrts, assign and edit backdrops
and load data from an array.

• 9. The Multimedia Control enables the users to control and manage t5he recording
playback of a variety of multimedia using a simple push-button interface.

• 10. The PictureClip Control enables the users to create an image resource for other
Visual Basic Controls by storing multiple images in a single image resource and then
retrie3ving individual images by ‘clipping’ specific regions.

• 11. The ProgressBar Control enables the users to get a feedback about a lengthy
operation by pictorially displaying a moving coloured bar.

• 12. The RichTextBox Control enables the users to get word-processing features in a
TextBox.

• 13. The Slider Control enables the users to select a range of data between a
maximum and a minimum setting.

• 14. The StatusBar Control enables the users to display text and images in the Status
Bar.

• 15. The Sysinfo Control enables the users to determine the current operating system,
how to monitor and respond to Plug and Play events or changes in AC and battery
power status.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


• 16. The Tabbed Dialog Control enables the users to present several dialogs or
screens of information on a single form using the same interface.

• 17. The ToolBar Control enables the users to reconfigure the Toolbar by setting the
AllowCustomize property.

• 18. The TabStrip Control enables the users to create tabs by adding tab objects to the
tab collection. Use an imagelist controlo to supply bitmaps for the tabs.

• 19 The TreeView Control enables the users to expland the node objects and explain
how they relate to each other.

• 20. The WinSock Control enables the users to send data to remote computers using
TCP or UDP protocols.

• 21. The ADO or ActiveX Data Model is another database object model like the
DAO model which is useful in certain cases

Developing Projects using these Activex Controls will form the subject matter for a few
more lessons to follow.

1. Project using the Timer Control:

A digital clock is a very simple but very useful application involving the timer control.
This project requires a timer and two labels. The running time will be displayed in one
label and the current date will be displayed in the other label. Timer is an Iintrinsic
ActiveX control and so is already present in the Tool Box. Drag one timer and two label
controls into the form. Give the labels appropriate size, font and border and set their
caption property blank. Set the timer interval property as 1000(one second) and the
Enabled property as True. The project at the design time looks as in the figure 4.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4

Entering the Event Codes:

Open the code window by double clicking the Timer control and enter the code as
shown in the figure 4a.

Private Sub Timer1_Timer()


If Label1.Caption <> CStr(Time) Then
Label1.Caption = Date
Label2.Caption = Time
End If
End Sub

Figure 4a.

Running the Project:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Select Start from the Run Menu. The clock will begin to run. The current date will
be displayed in the other label. The run mode window is as shown in the figure 5.
Another important point you notice is that the timer control does not appear in the run
mode, and is invisible, but works only from behind.

Figure 5

Building BarChart Project:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Bar Charts are very useful for displaying business data, say product sales versus years.
VB has an ActiveX control named Microsoft Chart Control, to draw two dimensional
and three dimensional bar charts.

Controls used in this project:

The MS Chart control is brought into the Toolbox from the component dialog box. If
it is not available in the dialog box, click the browse button and select the same from the
control files directory. The MSChart icon will appear in the tool box. It must be placed
in a bitmap container. So a picture box control is first drawn into the form. Then the
MSChart control is placed inside the picture box. Then a command button is placed in
the form. It is given the caption and name as ‘setchart’. The design window will look
as shown in the figure 6. The code window is opened by double clicking the setchart
button and the code is entered as shown in the figure 6a. Save the form as chartfrm and
the project as chartprj. Select start from the Run menu. You will have to enter 9 data
values in response to prompts. The bar chart will appear as shown in the figure 7.

Private Sub setchart_Click()


Dim i, j, k
MSChart1.RowCount = 3
MSChart1.ColumnCount = 3
MSChart1.chartType = VtChChartType2dBar
k = 1996
For i = 1 To 3
For j = 1 To 3
MSChart1.Row = i
MSChart1.Column = j
MSChart1.RowLabel = k
MSChart1.Data = InputBox("enter values for row " & i & " column " & j)
Next j
k=k+1
Next i
End Sub

Figure 6a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 6

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 7

3. Project using Combo Box:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


In this project we use 3 combo boxes to set different values for principal, ratepercent
and years and compute simple and compound interest for the different sets of values.
Drag 7 command buttons, 7 labels, 2 text boxes and 3 combo boxes in the form, size
them caption them and position them as shown in the figure 8. The different sets of
values for principal, ratepercent and years can be added either at design time or during
run time. If you want to add items during design time, set the list property. Check list in
the property box, then add items, pressing ctrl + enter after each item. To enter items at
run time you have to write codes. Items that are selected in the combo boxes can be
deleted by the delete buttons.. Open the code window and enter the codes as shown in
the figure 8a. Save and run the project and experiment with the different controls. A
typical run mode window is shown in the figure 9.

Figure 8

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Private Sub Command1_Click()
Text1.Text = Combo1.Text * Combo2.Text * Combo3.Text / 100
Text2.Text = Combo1.Text * (1 + Combo3.Text / 100) ^ Combo2.Text - Combo1.Text
End Sub

Private Sub Command2_Click()


principal = InputBox("enter principal to be added")Combo1.AddItem principal
End Sub

Private Sub Command3_Click()


Combo1.RemoveItem Combo1.ListIndex
End Sub

Private Sub Command4_Click()


ratepercent = InputBox("enter ratepercent to be added")
Combo3.AddItem ratepercent
End Sub

Private Sub Command5_Click()


years = InputBox("enter years item to be added")
Combo2.AddItem years
End Sub

Private Sub Command6_Click()


Combo2.RemoveItem Combo2.ListIndex
End Sub

Private Sub Command7_Click()


Combo3.RemoveItem Combo3.ListIndex
End Sub

Private Sub Command8_Click()


Text1.Text = principal * ratepercent * years / 100
End Sub
Private Sub Form_Load()
Combo1.AddItem 500
Combo1.AddItem 600
Combo1.AddItem 700
Combo2.AddItem 2.5
Combo2.AddItem 3.5
Combo3.AddItem 7.5
Combo3.AddItem 12.5
End Sub
Figure 8a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 9

Summary:

In this lesson we have described some three projects and learnt a few things about
ActiveX controls and their uses. In the next lesson we will consider some more ActiveX
Controls.
x--------------------------------------------x

Visual Basic-6
3. Projects using Intrinsic and Professional ActiveX Control(2)
In this Lesson we will explain some five Projects as shown below using ActiveX
Controls.

• Common Dialog Control


• RichTextBox Control
• DriveListBox, FileListBox, DirListBox and PictureBox Controls

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


• SS Tab Control
• MDI Form

1. Project using the Common Dialog Control:

The Common Dialog Control is first drawn into the Toolbox from Component Dialog
Menu. This dialog box gives support to use some of the dialog boxes supplied by
Windows 95 in your own projects. In the absence of this control you have to write codes
for creating such dialog boxes,. The dialog boxes supported by Common Dialog Control
are Open, Save, Print, PrintSetup, Font, Color and Help. Drag a Common Dialog
Control, and seven command buttons in the form. Give the name and caption property
of the Command buttons as shown in the figure 1.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 1

Entering codes for the Command Buttons:

Open the code window by double clicking the command button and write the code as
shown in the figure 1a.

Private Sub Color_Click()


' Show the dialog with an initial color and show the full dialog
' To use two flag parameters, simply add them together
CommonDialog1.Flags = cdCClFullOpen + cdlCCRGBInit
' Set currently selected color to blue
CommonDialog1.Color = RGB(0, 0, 255)
CommonDialog1.ShowColor
' Place color selected by user in variable
returnedColor = CommonDialog1.Color
End Sub

Private Sub Font_Click()

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


' Set flags to show both printer and screen fonts
' Alternately, use the flag cdlCFPrinterFonts or cdlCFScreenFonts to show a specific
set
CommonDialog1.Flags = cdlCFBoth
CommonDialog1.ShowFont
' Display selected font
MsgBox "Font Name: " & CommonDialog1.FontName & " Font Size: " &
CommonDialog1.FontSize, vbInformation, "Selected Font"
End Sub

Private Sub Help_Click()


' Show the VB help file
CommonDialog1.HelpFile = "VB.HLP"
' Display the contents of the file
CommonDialog1.HelpCommand = cdlHelpContents
CommonDialog1.ShowHelp
End Sub

Private Sub Open_Click()


' Clear current filename
CommonDialog1.filename = ""
' Show only text files to open
CommonDialog1.Filter = "Text Files|*.txt|All Files|*.*"
CommonDialog1.ShowOpen
' Check to make sure user selected a file
If CommonDialog1.filename <> "" Then
MsgBox "File: " & CommonDialog1.filename, vbInformation, "Selected file"
End If
End Sub

Private Sub Print_Click()


' Clear current flags
CommonDialog1.Flags = 0
CommonDialog1.ShowPrinter
End Sub

Private Sub PrintSetup_Click()


' Show print setup dialog
CommonDialog1.Flags = cdlPDPrintSetup
CommonDialog1.ShowPrinter
End Sub

Private Sub Save_Click()


' Set default save filename
CommonDialog1.filename = "Doc1.txt"
' Save as text file

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


CommonDialog1.Filter = "Text Files|*.txt"
CommonDialog1.ShowSave
End Sub

Figure 1a

Running the Project:

Select Start from the Run Menu. You will find the Common dialog box has become
invisible in the run mode window. The run mode window appears as in the figure 2. On
clicking the open button, you will get the open dialog window as in the figure 3. Click
the cancel button in the open dialog window . Now click the Save button to view the
Save window. Repeat this for viewing all the other windows and see that the project is
successful..

Figure 2

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 3

2. Project using RichTextBox Control:

The traditional text box control is ideal for text entry at a given font and size.
RichTextBox Control allows the user to enter text with varying fonts and sizes. Add the
RichTextBox control and the Common Dialog Control to the Toolbox by drawing them

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


from the component dialog box. Drag a RichTextBox control, Common Dialog Control
and a Command Btton control in the form. Set the command button caption and name as
font. A font dialog box can be opened only through the Common Dialog control. The
Common Dialog control box will be invisible during run time. .Save the form and the
project. The project at the design time looks as in the figure 4.

Figure 4

Entering the Code:

Open the code window by double clicking the font button. Enter the codes as shown
in the figure 4a and finally save the project.

Private Sub Font_Click()


'Show both printer and screen fonts
CommonDialog1.Flags = cdlCFBoth
CommonDialog1.ShowFont
RichTextBox1.SelFontName = CommonDialog1.FontName
RichTextBox1.SelFontSize = CommonDialog1.FontSize
RichTextBox1.SelBold = CommonDialog1.FontBold
RichTextBox1.SelItalic = CommonDialog1.FontItalic

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


RichTextBox1.SetFocus
End Sub

Figure 4a

Running the Project:

Select Start from the Run menu. You type any text in the RichTextBox and select it.
Click the font button. The font dialog box will open. Set the desired font and size. On
deselecting

the text, you will find the text printed in the desired font and size. The run mode
window is shown in the figure 5.

Figure 5

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


3. Project using DriveListBox, FileListBox, DirListBoc and ImageBox:

In this project, the DriveListBox, the FileListBox and theDirListBox are coordinated
to disk access without any programming. One can select a gif file from the disk and load
it in the Image box. The four controls are drawn into the design window and arranged
as shown in the figure 6. In this example we are going todisplayThe ImageBox control
simply appears as empty rectangle in the design mode. At run time it will be loaded by
the a .gif files. So change the Pattern property of the FileListBox from its default to
*.gif.

Figure 6

Entering the Code:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Open the code window by double clicking the DirListBox. The codes are entered as
shown in the figure 6a.

Private Sub Dir1_Change()


File1.Path = Dir1.Path
End Sub

Private Sub Drive1_Change()


Dir1.Path = Drive1.Drive
End Sub

Private Sub File1_DblClick()


Image1.Picture = LoadPicture(File1.Path & "\" & File1.filename)
End Sub

Figure 6a

The run mode window looks as in the figure 7. The gif file is selected by
suitably changing the path list, directory list and finally selecting the required file.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 7

4. Tabbed Dialog Control:

Suppose you want to include a large number of controls in a single form you can
divide the form into something like pages using this Tabbed Dialog Control or SS
Tab Control. When you drag the SS Tab Control in the form it presents a
container with tabs at the top. Each tab corresponds to a page of the form. You
can add any number of pages by simply increasing the value of the ‘the
TabsPerRow’ property. Each page can contain a number of components. The
figure 8 shows a form with 4 tabs with some controls placed in tab1. Similarly you
can place controls in other tabs or pages.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 8

5. Multiple document Interface:

The MDI was designed to simplify the exchange of information among documents, all
under the same roof. With a MDI application, you can maintain multiple windows, but
not multiple copies of the application. Data exchange is easier when you can view and
compare many documents simultaneously. The main form or MDI form is not
duplicated, but it acts as a container for all the windows, and it is called the parent
window.

A MDI application must have at least two forms, the parent form and one or more
child forms. There can be many child forms, but only one parent form. He parent form
may not contain controls. While the parent form is open in the design mode, though the

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


icons in the toolbox are not disabled, but you cannot place any control on the form. But
you can place controls in child forms.

To create a MDI application follow these steps:

1. Start a new project, and choose Project>Add MDI form to add the form
2. Set the form’s caption to MDIwindow.
3. Choose Project>Add form to add a regular form.
4. Make this form child by setting its MDIChild property true. To denote that this is a
child form set its caption to MDIChild.
5. Double-click your picture control in the tool box. It will appear as toolbar to your
MDI form.
6. Place three command buttons on this toolbar and change their names and captions to
newchild, cascade and tile respectively.
7. The MDI window will look as in the figure 9.
8. Enter the codes as shown in the figure 9a.
9. Save and run the project.
10. See how you can arrange the child windows in tiles or cascades. You cannadd any
number of child windows by clicking the newchild button. A typical tile
arrangement of child windows is shown in the figure 10 and cascade arrangement of
the child windows in the figure 11.

Dim i
Private Sub cascade_Click()
MDIForm1.Arrange 0
End Sub

Private Sub newchild_Click()


Dim obj As Form1
Set obj = New Form1
obj.Caption = obj.Caption & i
obj.Show
i=i+1
End Sub

Private Sub MDIForm_Load()


i=2
End Sub

Private Sub tile_Click()


MDIForm1.Arrange 1
End Sub

Figure 9a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 9

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 10

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 11

x--------------------------------x

Visual Basic-6
4. Projects using Intrinsic and Professional ActiveX
Controls(3)

In this lesson we will consider four projects using the following ActiveX controls.

• 1. TreeView Control
• 2. ProgressBar Control
• 3. Drag-and-Drop Operation
• 4. WebBrowser Control

1. Project using TreeView Control:

The TreeView control is used to organise information in a hierarchial, structure. The


TreeView Control allows you to place information into an outline format similar to the

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


one we see in Windows Explorer. The figure 1 shows the type of organization which
we require and this is the run mode window of our project. Drag a TreeView Control
and three Command buttons in the form. Set the caption and the name property of the
buttons as shown in the figure
2 and arrange the controls accordingly.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Entering the Code:

Open the Code window and enter the codes for the three command buttons as shown
in the figure 1a.

Private Sub Command1_Click()


Dim nodx As Node
Set nodx = TreeView1.Nodes.Add(, , "R", "FoodTypes")
Set nodx = TreeView1.Nodes.Add("R", tvwChild, "Ft", "Fruits")
Set nodx = TreeView1.Nodes.Add("R", tvwChild, "Vg", "Vegetables")
Set nodx = TreeView1.Nodes.Add("R", tvwChild, "Mt", "Meat")
Set nodx = TreeView1.Nodes.Add("R", tvwChild, "Jf", "Juicy Food")
Set nodx = TreeView1.Nodes.Add("R", tvwChild, "Sf", "Salty Snacks")
nodx.EnsureVisible
End Sub

Private Sub Command2_Click()


Set nodx = TreeView1.Nodes.Add("Ft", tvwChild, "Ap", "Apple")
Set nodx = TreeView1.Nodes.Add("Ft", tvwChild, "Or", "Orange")
Set nodx = TreeView1.Nodes.Add("Ft", tvwChild, "Pr", "Pear")
End Sub

Private Sub Command3_Click()


Set nodx = TreeView1.Nodes.Add("Vg", tvwChild, "Bn", "Beans")
Set nodx = TreeView1.Nodes.Add("Vg", tvwChild, "Cr", "Carrot")
Set nodx = TreeView1.Nodes.Add("Vg", tvwChild, "Rd", "Raddish")
End Sub

Figure 1a

Running the Project:

On selecting the start button from the Run menu, the run mode window aoppears.
Now click the createlist button. It will first create the first level list. Then click the
addfruit button. The fruits list will be added at the second level.. Then click the addveg
button. The vegetables list will be added at the second level and the final window
appears as shown in the figure 1.

2. Project using ProgressBar:

The ProgressBar Control is used to pictorially represent the progress of a lengthy


computer operation, say file copying or doing complex computations etc. An advancing
rectangular bar will usually denote the progress. Drag a ProgressBar Control, a Text box
and a command button and locate them in the form as shown in the figure 3.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 3

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Entering the code:

Open the code window of the PictureBox and enter the code as shown in the figure 3a.
Select the Start button from the Run Menu and click the start button. The run mode
window shows the progress of the computation by an advancing rectangular bar and
comes to a stop when the computation is over. The Text box shows the percentage of
progress completed. The run mode window is shown in the figure 4.

Private Sub cmdStart_Click()


' Set minimum and maximum values for progress
ProgressBar1.Min = 1
ProgressBar1.Max = 5000
' Loop 5000 times
For i = 1 To 5000
' Set current value to loop value so progress will show status
ProgressBar1.Value = i
Text1 = CStr(i / 50) + "%completed"
Next i
' Tell user routine is complete
MsgBox "Done", vbInformation, "Complete."
End Sub

Figure 3a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


3. Project involving Drag-Drop Operations:

Many of the controls in VB-5 have a DragMode property which determines whether a
control can be dragged or not with the mouse. In this project the drag property of a
command button is illustrated by dragging it over a PictureBox Control. Drag a
PictureBox and a commands button and position them as shown in the figure 5. Set the
DragMode property of the button as 1-automatic. Open the code window of the
PictureBox and enter the code as shown in the figure 5a.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 5a

Private Sub Picture1_DragDrop(Source As Control, X As Single, Y As Single)


Picture1.BackColor = vbBlue
End Sub

Private Sub Picture1_DragOver(Source As Control, X As Single, Y As Single, State As


Integer)
If State = 0 Then Picture1.BackColor = vbRed
If State = 2 Then Form1.Caption = "source control moves over the PictureBox"

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


If State = 1 Then
Picture1.BackColor = vbGreen
Form1.Caption = "Drag and Drop demo"
End If
End Sub
Figure 5a

On running the project you will notice that when the button is first dragged over the
picture box, it is paintede red. When the button leaves the picture box, the picture box is
painted green. If the user drops the button while it is over the picture box, the picure box
is painted blue. The run mode window is shown in the figure 6.

Figure 6

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


4. Project using WebBrowser:

The WebBrowser ActiveX control acts like an Internet Explorer and so can be used to
view all html documents, Thus it becomes possible to view all web pages from within
Visual Basic.
oject using WebBrowser:

Select Microsoft Internet Controls from the Component Dialog box and place them in
the Toolbox. The Web Browser control appears as a globe in the tool box. Drag a Web
Browser, a common dialog and a command button control in the design form. The
WebBrowser will appear as empty rectangle and increase its size to the maximum extent
possible. Change the Caption property of the command button as ‘browse’. The design
window will look as shown in the figure7.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 7

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Entering the Event Code:

Open the code window by double clicking the command button and enter the code as
shown in the figure 7a.

Private Sub Command1_Click()


CommonDialog1.Filter = "HTML Files|*.HTM|Text Files| *.Text|All Files|*.*"
CommonDialog1.ShowOpen
If CommonDialog1.filename <> "" Then
WebBrowser1.Navigate CommonDialog1.filename
End If
End Sub

Figure 7a

Running the Project:

Select Start from the Run Menu. Then click the command button. The Commmon
dialog box will help you by displaying the file open dialog box. Browse through the
folders and select a html document. In this case we have selected a html document
containing a VBScript Program for printing the calender for the current month. The html
document looks as in the figure 7b. The run mode window appears as in the figure 8.
You will ,find that the calender is displayed for the current month. In fact you can
browse any HTML document with this Web Browser.

<html>
<script language="vbscript">
dim imonth, thisdate, nextday, cday
imonth = month(date)
document.write "<center>"
document.write "<font face='verdanna' size=5>"
document.write "Calendar for " &date
document.write "<p>"
document.write "<table cellpadding=10 border><tr>"
document.write "<td><b>sun<td><b>mon<td><b>tue<td><b>
wed<td><b>thu<td><b>fri<td><b>sat"
document.write "<tr>"
thisdate=DateSerial(year(date), month(date), 1)
nextday=1
for cday = 1 to 7
if WeekDay(thisdate) > cday Then
document.write "<td></td>"
else
document.write "<td align=center> <font size=3>" & nextday
& "</td>"

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


nextday = nextday + 1
thisdate =DateSerial(year(date), imonth, nextday)
end if
Next
document.write "<tr>"
weekdays = 1
while month(thisdate) = imonth
document.write "<td align=center><font size=3>" & nextday
& "</td>"
nextday = nextday + 1
weekdays = weekdays + 1
if weekdays > 7 Then
weekdays = 1
document.write "<tr>"
end if
thisdate = DateSerial(year(date), imonth, nextday)
wend
document.write "</table>"
document.write "</center>"
</script>
</html>

Figure 7b

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 8

x--------------------------------------------------------------x

Visual Basic-6
5. Projects using Intrinsic and Professional ActiveX
Controls(4)

In this lesson we will consider the construction of the following Graphic Projects:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


• 1. Drawing the graph for any function
• 2. Drawing Pie Chart
• 3. Colored Pixels
• 4. Color Gradient

One can place Graphics on three controls:

1. Form
2. PictureBox
3. ImageBox

The main difference between these three controls is that the ImageBox is specially
designed for displaying bitmaps, whereas the other two controls provide drawing
methods, which let you design graphics at run time.

1. Project for Graphing any Function:

Drag a Picture box, and two command button in the form, size them, caption them
and position them as shown in the figure 1. Open the code window of the command
button and enter the codes as shown in the figure 1a. Save and run the project. You will
get the graph for the function cos(3x)*sin(5x). You can try with different types of
functions and see how the scale properties are calculated for each function and the graphs
are drawn. A typical output is shown in the figure 2.

Private Sub Command1_Click()


Dim t, functionval As Double
Dim xmin, xmax, ymin, ymax As Double
ymin = 1E+33: ymax = -1E+33
xmin = 2: xmax = 10
Picture1.Cls
Picture1.ScaleMode = 3
xpixels = Picture1.ScaleWidth - 1
'calculate min and max for y axis
For i = 1 To xpixels
t = xmin + (xmax - xmin) * i / xpixels
functionval = functioneval1(t)
If functionval > ymax Then ymax = functionval
If functionval < ymin Then ymin = functionval
Next
'set a user defined scale mode
Picture1.Scale (xmin, ymin)-(xmax, ymax)
'plot the function
For i = 0 To xpixels
t = xmin + (xmax - xmin) * i / xpixels
Picture1.Line -(t, functioneval1(t))

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Next
End Sub

Function functioneval1(ByVal x As Double) As Double


functioneval1 = Cos(3 * x) * Sin(5 * x)
End Function

Private Sub Command2_Click()


End
End Sub

Figure 1a

Figure 1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


2. Project for Drawing a Piechart:

The Piechart application uses the Circle method to draw pie charts with connected
arcs. Because a connected arc is a closed shape, it can also be filled with a pattern or a
solid color as specified by the FillStyle and FillColor properties.

The program generates 10 random numbers in the range 20 to 100, stores them in the
piedata() array, and then calculates the arc that corresponds to each number. Because the
total must be a full circle, each element of the piechart() array corresponds to an arc of
2*pi*piedata()/total. Each slice’s starting angle is the ending angle of the previous slice,
and its ending angle is the starting angle plus the angle corresponding to the element in
the piedata array.

Drag two check boxes and three command buttons from the Toolbox, caption them,
size them and position them as shown in the figure 3. Open the code window of the
command buttons and enter the codes as shown in the figure 4a.. Save and run the
application. The run mode window will appear as in the figure 4.

Private Sub Command1_Click()


Dim pieData(10) As Integer
Form1.Cls
For i = 0 To 9
pieData(i) = 20 + Rnd() * 100
Total = Total + pieData(i)
Next
Form1.DrawWidth = 3
For i = 0 To 9
arc1 = arc2
arc2 = arc1 + 6.28 * pieData(i) / Total
If Check1.Value Then
Form1.FillStyle = 2 + (i Mod 5)
Else
Form1.FillStyle = 0

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


End If
If Check2.Value Then
Form1.FillColor = QBColor(8 + (i Mod 6))
Else
Form1.FillColor = QBColor(9)
End If
Form1.Circle (Form1.ScaleWidth / 2, Form1.ScaleHeight / 2), Form1.ScaleHeight / 2.5, ,
-arc1, -arc2
Next
End Sub

Private Sub Command2_Click()


End
End Sub

Private Sub Command3_Click()


Form1.Cls
End Sub

Figure 4a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 3

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4

3. Colored Pixels:

Pixels are created using the Pset method and they are colored randomly using the QB
color function. Drag two command buttons on the form and position them as shown in
the figure 5. Open the code window of the command buttons and enter the code as
shown in the figure 6a. Save and run the project. You will find the pixels are created in
random colors. The output will look as in the figure 6.

Private Sub Command1_Click()


Dim cx, cy, msg, xpos, ypos
ScaleMode = 3
DrawWidth = 5

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


ForeColor = QBColor(4)
FontSize = 24
cx = ScaleWidth / 2
cy = ScaleHeight / 2
Cls
msg = "happy new year"
CurrentX = cx - TextWidth(msg) / 2
CurrentY = cy - TextHeight(msg)
Print msg
Do
xpos = Rnd * ScaleWidth
ypos = Rnd * ScaleHeight
PSet (xpos, ypos), QBColor(Rnd * 15)
DoEvents
Loop
End Sub

Private Sub Command2_Click()


End
End Sub

Figure 6a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 5

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The program shown in the figure 7a is intended to display a gradient of colors in a
picture box. The design window consists of one picture box and a command button as
shown in the figure 7. On executing this program you will find a color gradient filling
the picture box as shown in the figure 8. You can try with different starting and ending
colors by changing the RGB values.

Private Sub Command1_Click()


Dim newcolor As Long
Dim ipixel, pwidth As Integer
Dim redinc, greeninc, blueinc As Single
Dim color1 As Long, color2 As Long
color1 = RGB(255, 255, 0)
color2 = RGB(0, 0, 0)
startred = getred(color1)
endred = getred(color2)
startgreen = getgreen(color1)
endgreen = getgreen(color2)
startblue = getblue(color1)
endblue = getblue(color2)
pwidth = Picture1.ScaleWidth
redinc = (endred - startred) / pwidth
greeninc = (endgreen - startgreen) / pwidth
blueinc = (endblue - startblue) / pwidth
For ipixel = 0 To pwidth - 1
newcolor = RGB(startred + redinc * ipixel, startgreen + greeninc * ipixel, startblue +
blueinc * ipixel)
Picture1.Line (ipixel, 0)-(ipixel, Picture1.Height - 1), newcolor
Next
End Sub

Function getred(colorval As Long) As Integer


getred = colorval Mod 256
End Function

Function getgreen(colorval As Long) As Integer


tgreen = ((colorval And &HFF00FF) / 256&)
End Function

Function getblue(colorval As Long) As Integer


getblue = (colorval And &HFF0000) / (256& * 256&)
End Function

Figure 7a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 7

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 8

x---------------------------------------x

Visual Basic-6
6. Menu-Driven and Calculator Projects

In this lesson we will consider two projects, one a menu driven drawing project and
the other a calculator project. Menus are one of the most important and most
characteristic elements of the Windows User Interface. Menu Commands are similar to
Controls. They recognize only the click events. When you group controls as arrays,
give them the same name property, but give their index property as 0, 1, 2, 3 etc. to
distinguish them.

1. Menu Driven Project:

A view of the Menu bar and some Menu Items:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Suppose we want to build a program with a menu bar with two titles and one or more
menu items for each of the menu titles somewhat as shown in the figure 1. In this
example the menu items denote different pixel values for drawing lines. The different
menu items are connected to appropriate codes which will enable you to select the pixel
thickness from the menu and draw figures of of different thickness.

Figure 1

Menu Editor Window:

Start VB from the Standard EXE mode. Select the item “Menu Editor” from the
Tools Menu. The Menu Editor Window appears as shown in the figure 2. This window
lets you create a menu bar that contains all the menu items you want.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2

Creating the Menu Bar:

In this project we will have only two menu titles in the menu bar. Of course one can
have as many as required for the concerned problem. The first title is ‘Draw’. Type
‘&Draw’ in the Caption field. The & symbol before D tells that D is a hot key and users
can use alt+D key combination to pull down the menu. Next press the Tab key. This
moves the insertion point to the next text box ‘Name’, which is the name of the control.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Enter ‘menDraw’ in the Name field and click the right arrow key at the bottom of the
menu editor window. This is how the computer recognizes the item as menu title. The
prefix ‘men’ is used to indicate to the users that the item ‘Draw’ is the name of the menu
title. The Caption field is cleared to enable the next menu title to be entered. Now enter
‘&Quit’ in the Caption field and ‘menQuit’ in the Name field and click OK. Now the
design window will show a menu bar with two items ‘Draw’ and ‘Quit’. At the bottom
you will see the two items entered as shown in the figure 2a.

&Draw
&Quit

Figure 2a

Creating Menu Items:

Now we have to enter the menu items under the menu titles Draw and Quit. B Open
the Menu Editor Window. Select &Quit. Select Insert. This action will insert a line
between the two items. Type &Erase in the Caption field and miErase in the Name field.
The prefix ‘mi’ indicates that the item ‘Erase’ is a menu item and not a menu title. Now
the bottom window will appear as shown in the figure 2b.

&Draw
…&Erase
&Quit

Figure 2b

In a similar manner add the menu item Exit for the menu title Quit. Use the Caption
name as E&xit and the control name as miExit.

Adding Control Arrays:

Next we have to add the three line-width menu items. The first one will have the
Caption &1 Pixel and a control name ‘miPixel’ When different controls have the same
array name they must be identified by indexes. So after entering the control name, move
the insertion point to the index field and enter 1 for the first Pixel Control. For the
subsequent Pixel Controls enter the index values as 2 and 3 respectively.

Inserting Lines in Menus

After highlighting the item next to the place where you want to insert a line, select
insert button. Type a hyphen(-) symbol for the Caption name and miLine1 for the
Control name. For subsequent lines give the control names as muLine2, miLine3 etc.
Finally the design window will appear as shown in the figure 3. Insertion or deletion of

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


lines and menu titles and menu items can be done with the help of insert, delete and OK
buttons.

Entering Codes for the Controls and Pop-up Menu:

When you select any control, the code window for the particular control will be
opened. Enter the codes for the different controls as shown in the figure 3a. A pop-up
menu is the same as the other menus, except that it does not drop down from the menu
bar, but displayed on the form at the place where you right-click the mouse. The code
for creating the pop-up menu is also shown in the figure 3a.

Private numPoints As Integer ' Number of points saved


Private saveX(1000) As Single ' Saved X coordinates
Private saveY(1000) As Single ' Saved Y coordinates
Private numLines As Integer ' Number of separate lines
Private lineStart(500) As Integer ' Start of each line
Private lineEnd(500) As Integer ' End of each line
Private lineThickness(500) As Integer ' DrawWidth for
' each line
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As
Single)
PSet (X, Y) ' Draw first point in line
numPoints = numPoints + 1 ' The next free point
saveX(numPoints) = X ' Remember this point
saveY(numPoints) = Y
numLines = numLines + 1 ' Next free line
lineStart(numLines) = numPoints ' Index of the first point
lineEnd(numLines) = numPoints ' Initially a single point
End Sub
lineThickness(numLines) = DrawWidth
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As
Single)
If Button = 1 Then ' Is the left button down?
Line -(X, Y) ' Yes, draw a line
numPoints = numPoints + 1 ' Next free point in array
saveX(numPoints) = X ' Remember this point
saveY(numPoints) = Y
lineEnd(numLines) = numPoints ' New ending index for line
End If
End Sub

Private Sub Form_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As


Single)
If Button = 2 Then 'Right mouse button clicked?
PopupMenu menDraw 'Yes. Display menDraw as popup.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


End If
End Sub

Private Sub Form_Paint()


For Lin = 1 To numLines ' Draw each line
aStart = lineStart(Lin) ' Start index of this line
anEnd = lineEnd(Lin) ' End index of this line
DrawWidth = lineThickness(Lin)
PSet (saveX(aStart), saveY(aStart))
For i = aStart To anEnd ' Draw parts of this line
Line -(saveX(i), saveY(i))
Next i
Next Lin
End Sub

Private Sub miErase_Click()


Cls
numPoints = 0 ' Set to no points
numLines = 0 ' Set to no lines
End Sub

Private Sub miexit_Click()


End
End Sub

Private Sub miPixel_Click(Index As Integer)


miPixel(DrawWidth).Checked = False ' Uncheck current width
DrawWidth = Index ' Change width of the pen
miPixel(Index).Checked = True ' Check the new width
End Sub

Private Sub miPrint_Click()


For Lin = 1 To numLines ' Draw each line
aStart = lineStart(Lin) ' Start index of this line
anEnd = lineEnd(Lin) ' End index of this line
Printer.DrawWidth = lineThickness(Lin)
Printer.PSet (saveX(aStart), saveY(aStart))
For i = aStart To anEnd ' Draw parts of this line
Printer.Line -(saveX(i), saveY(i))
Next i
Next Lin
Printer.EndDoc
End Sub
Figure 3a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Running the Project:

Select Start from the Run Menu. Then by clicking the menu items draw the word
hello for three different thickness. The final run mode window will look as shown in the
figure 4.

Figure 3

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


2. Calculator Project:

The basic layout of the screen is shown in the figure 5. There are two control
arrays of buttons one for the digits 0 to 9 and another for operators +, -, /, * and =.
The form is given the name ‘calculator’ and its icon property is set to calculator
icon. The display label is given the name ‘Readout’ and the caption ‘0.’. The
number buttons 0 to 9 are given the same name ‘Number’, their captions and
indexes are set as 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9 respectively. The operator buttons /,
+, X, - and = are given the same name, “Operator” , and their indexes are set as 0, 1,
2, 3 and 4 respy. The ‘%’ button is given the name ‘Percent’, the ‘.’ button is
given the name ‘Decimal’, the ‘C’ button is given the name ‘Cancel’ and the ‘CE’
button is given the name ‘CancelEntry’. The codes are entered in the code window
as shown in the figure 5a. Save and run the project and check that the calculator
functions properly.

Option Explicit
Dim Op1, Op2 ' Previously input operand.
Dim DecimalFlag As Integer ' Decimal point present yet?
Dim NumOps As Integer ' Number of operands.
Dim LastInput ' Indicate type of last keypress event.
Dim OpFlag ' Indicate pending operation.
Dim TempReadout
' Click event procedure for C (cancel) key.
' Reset the display and initializes variables.
Private Sub Cancel_Click()
Readout = Format(0, "0.")
Op1 = 0
Op2 = 0
Form_Load
End Sub
' Click event procedure for CE (cancel entry) key.
Private Sub CancelEntry_Click()
Readout = Format(0, "0.")
DecimalFlag = False
LastInput = "CE"
End Sub
' Click event procedure for decimal point (.) key.
' If last keypress was an operator, initialize
' readout to "0." Otherwise, append a decimal
' point to the display.
Private Sub Decimal_Click()
If LastInput = "NEG" Then
Readout = Format(0, "-0.")
ElseIf LastInput <> "NUMS" Then
Readout = Format(0, "0.")

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


End If
DecimalFlag = True
LastInput = "NUMS"
End Sub

' Initialization routine for the form.


' Set all variables to initial values.
Private Sub Form_Load()
DecimalFlag = False
NumOps = 0
LastInput = "NONE"
OpFlag = " "
Readout = Format(0, "0.")
'Decimal.Caption = Format(0, ".")
End Sub
' Click event procedure for number keys (0-9).
' Append new number to the number in the display.
Private Sub Number_Click(Index As Integer)
If LastInput <> "NUMS" Then
Readout = Format(0, ".")
DecimalFlag = False
End If
If DecimalFlag Then
Readout = Readout + Number(Index).Caption
Else
Readout = Left(Readout, InStr(Readout, Format(0, ".")) - 1) +
Number(Index).Caption + Format(0, ".")
End If
If LastInput = "NEG" Then Readout = "-" & Readout
LastInput = "NUMS"
End Sub
' Click event procedure for operator keys (+, -, x, /, =).
' If the immediately preceeding keypress was part of a
' number, increments NumOps. If one operand is present,
' set Op1. If two are present, set Op1 equal to the
' result of the operation on Op1 and the current
' input string, and display the result.
Private Sub Operator_Click(Index As Integer)
TempReadout = Readout
If LastInput = "NUMS" Then
NumOps = NumOps + 1
End If
Select Case NumOps
Case 0
If Operator(Index).Caption = "-" And LastInput <> "NEG" Then
Readout = "-" & Readout

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


LastInput = "NEG"
End If
Case 1
Op1 = Readout
If Operator(Index).Caption = "-" And LastInput <> "NUMS" And OpFlag <> "="
Then
Readout = "-"
LastInput = "NEG"
End If
Case 2
Op2 = TempReadout
Select Case OpFlag
Case "+"
Op1 = CDbl(Op1) + CDbl(Op2)
Case "-"
Op1 = CDbl(Op1) - CDbl(Op2)
Case "X"
Op1 = CDbl(Op1) * CDbl(Op2)
Case "/"
If Op2 = 0 Then
MsgBox "Can't divide by zero", 48, "Calculator"
Else
Op1 = CDbl(Op1) / CDbl(Op2)
End If
Case "="
Op1 = CDbl(Op2)
Case "%"
Op1 = CDbl(Op1) * CDbl(Op2)
End Select
Readout = Op1
NumOps = 1
End Select
If LastInput <> "NEG" Then
LastInput = "OPS"
OpFlag = Operator(Index).Caption
End If
End Sub
' Click event procedure for percent key (%).
' Compute and display a percentage of the first operand.
Private Sub Percent_Click()
Readout = Readout / 100
LastInput = "Ops"
OpFlag = "%"
NumOps = NumOps + 1
DecimalFlag = True
End Sub

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 5a

Figure 5

x-----------------------------------------x

Visual Basic-6
7. Animation Projects
In this lesson we will consider some three projects involving animation. Animation is
caused by the motion of inanimate objects.

1. Project using Animation Control:

The Animation control allows you to create buttons which display animations
appropriate to the function perfomed by the computer. For example, when a filecopy

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


operation is perfomed, it will be appropriate when such a function is visually denoted by
flying something from the source to the destination. In Windows 95, this function is
denoted by pieces of paper flying from one folder to another folder. Drag an animation
control, a Common Dialog Control and two command buttons from the Toolbox. The
animation control will work only with silent avi files. Change the Caption property of
command buttons as ‘play’ and ‘stop’ respectively and arrange them in the design
window as shown in the figure 1.

Entering the code:

Open the code window by doubleclicking the command button and enter the codes as
shown in the figure 1a.

Private Sub Command1_Click()


CommonDialog1.ShowOpen
Animation1.Open CommonDialog1.filename
Animation1.AutoPlay = True
End Sub

Private Sub Command2_Click()


Animation1.Close
Animation1.Stop
End Sub

Figure 1a

Running the Project:

Select the Start button from the Run Menu. The run mode window appears on the
screen. On clicking the play button, a file open dialog box appears. You will find a
number of avi files in the directory given by \program files\devstudio\vb\graphics\avi\ .
On selecting the file the animation display appears on the screen as shown in the figure 2.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


2. Blinker Project:

In this project we draw two picture boxes and two timers in the design form. Two
command buttons are included to start and stop the blinking operations. The blinker
design window looks as in the figure 3. The codes for the timers, form and the command
buttons are entered in the code window as shown in the figure 3a. The project is saved
and given the Run command. The run mode window looks as in the figure 4. On
clicking the start button, the two picture boxes begin to blink one in red and another in
blue colors. On clicking the stop button blinking stops.

Option Explicit
Private color1 As Long
Private color2 As Long

Private Sub Command1_Click()


Timer1.Interval = 500
Timer2.Interval = 300
Timer1.Enabled = True
Timer2.Enabled = True
End Sub

Private Sub Command2_Click()


Timer1.Enabled = False
Timer2.Enabled = False
End Sub

Private Sub Timer1_Timer()


If color1 = vbRed Then
color1 = vbGreen
Else
color1 = vbRed
End If
Picture1.BackColor = color1
End Sub

Private Sub Form_Load()


color1 = vbRed
color2 = vbBlue
Picture1.BackColor = color1
Picture2.BackColor = color2
End Sub

Figure 3a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 3

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4

3. A Juggler Project:

In this project a juggler will appear to be moving and at the same time juggling with
three balls in his hands. Drag 5 picture boxes and one timer in the form and make the
design window look as shown in the figure 5. Set the timer interval property as 100.
Enter the codes as shown in the figure 5a. Save the project and bring it to the run mode.
The run mode window looks as in the figure 6. You can see the juggler moving and
juggling. In this project we load the picture file successively in 5 positions at short
regular intervals. This gives the illusion of motion.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Dim i As Integer
Private Sub Form_Load()
i=0
End Sub

Private Sub Timer1_Timer()


If i = 0 Then
Image5.Picture = LoadPicture
Image1.Picture = LoadPicture("c:\vbproj\juggler0.gif")
i=i+1
ElseIf i = 1 Then
Image1.Picture = LoadPicture
Image2.Picture = LoadPicture("c:\vbproj\juggler1.gif")
i=i+1
ElseIf i = 2 Then
Image2.Picture = LoadPicture
Image3.Picture = LoadPicture("c:\vbproj\juggler2.gif")
i=i+1
ElseIf i = 3 Then
Image3.Picture = LoadPicture
Image4.Picture = LoadPicture("c:\vbproj\juggler3.gif")
i=i+1
ElseIf i = 4 Then
Image4.Picture = LoadPicture
Image5.Picture = LoadPicture("c:\vbproj\juggler4.gif")
i=i+1
Else
i=0
End If
End Sub

Figure 5a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 5

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 6

x-----------------------------------------------------------x

Visual Basic-6
8. Project using Multiple Forms

In this lesson we will consider a project using four forms. In VB, the Form is the
container for all the controls that make up the user interface. A form has a title bar , on
which the form’s caption is displayed. On the right side of the title bar are three buttons-
Maximize, Minimize and Close. Each form is designed to operate independently of the
others, and they can communicate via global variables. In other situations one form can
be controlled from within another. This means you can manipulate the properties of the
controls in one form, from within another form. But you cannot capture the events of one
form’s controls in another form.

Creating Forms:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


When you open the Standard Exe window, you get the first form entitled as form1.
For adding a form select ‘Add Form’ from the Project menu and then select the Form
icon from the Add Form Dialog Window. The second form is added, entitled as form2.
In a similar manner you can add any number of forms. When the project is finally saved,
you will be presented with form save dialog for each form. You can give appropriate
names for each of the forms. Of course when the project is subsequently opened, all the
forms in the project are automatically opened and also saved when the project is saved.

Description of the Forms:

The first form called the main form contains the titles of the other projects to which
one can branch by clicking the appropriate button. The layout of the main form
(main.frm) is as shown in the figure 1. It contains a menu bar with two titles, ‘File’ and
‘Options’. The File Menu has only one item namely, ‘Exit’. The Options menu has 3
items namely, ‘Test Buttons’, Check Box’, and ‘Option Buttons’.. It has 4 command
buttons with their captions changed to ‘Test Buttons’, ‘Check Box’, ‘Option Button’ and
‘Exit’ respectively. The codes of the controls used in the main form are entered as
shown in the figure 1a.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 3

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4

Private Sub cmdButtons_Click()


' invoke a Click event in the menu
mnuButtons_Click
End Sub
Private Sub cmdCheck_Click()
' invoke a Click event in the menu
mnuCheck_Click
End Sub
Private Sub cmdExit_Click()

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Unload Me ' unload the form
End ' end the application
End Sub
Private Sub cmdOption_Click()
' invoke a Click event in the menu
mnuOption_Click
End Sub

Private Sub Form_Load()


frmMain.Height = 3600
frmMain.Width = 4965
End Sub

Private Sub mnuButtons_Click()


' display the form
frmButton.Show
End Sub

Private Sub mnuCheck_Click()


' display the form
frmCheck.Show
End Sub

Private Sub mnuFileExit_Click()


' invoke a Click event in the command button
cmdExit_Click
End Sub

Private Sub mnuOption_Click()


' display the form
frmOptions.Show
End Sub

Figure 1a

The second form is buttons.frm. It contains an image box, two command buttons and
a label. The picture property of the image box is associated with a traffic icon which
comes along with Windows 95. The traffic icon contains three circles filled with red,
green and amber colors respy. By clicking the change button or any one of the colored
circles, one colored circle can be highlighted. The controls are arranged as shown in the
figure 2 and the codes are entered as in the figure 2a in the code window of the buttons
form.

Private Sub ChangeSignal()


' Check to see what color the light is, and then change

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


' it to the next color. The order is green, yellow,
' and then red.
If imgGreen.Visible = True Then
imgGreen.Visible = False
imgYellow.Visible = True
ElseIf imgYellow.Visible = True Then
imgYellow.Visible = False
imgRed.Visible = True
Else
imgRed.Visible = False
imgGreen.Visible = True
End If
End Sub
Private Sub cmdChange_Click()
Call ChangeSignal ' Call the ChangeSignal procedure.
End Sub
Private Sub cmdClose_Click()
Unload Me ' Unload this form.
End Sub

Private Sub imgGreen_Click()


Call ChangeSignal ' Call the ChangeSignal procedure.
End Sub

Private Sub imgRed_Click()


Call ChangeSignal ' Call the ChangeSignal procedure.
End Sub

Private Sub imgYellow_Click()


Call ChangeSignal ' Call the ChangeSignal procedure.
End Sub

Figure 2a

The third form is check.frm. It contains a frame containing two option buttons, three
independent option buttons, two labels and one command button. The captions are given
as in the figure 3 and positioned. The code window for this form is opened and the
codes are entered as shown in the figure 3a.

' set up two string variables to hold the captions


Dim strComputer As String
Dim strSystem As String

Sub DisplayCaption()
' concatenate the caption with the two string

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


' variables.
lblDisplay.Caption = "You selected a " & _
strComputer & " running " & strSystem
End Sub

Private Sub cmdClose_Click()


Unload Me 'unload the form
End Sub

Private Sub Form_Load()


' invoke a Click event in the default options
' to update the label caption
opt486_Click
optWin95_Click
End Sub

Private Sub opt486_Click()


' assign a value to the first string variable
strComputer = "486"
' call the subroutine
Call DisplayCaption
End Sub

Private Sub opt586_Click()


' assign a value to the first string variable
strComputer = "Pentium"
' call the subroutine
Call DisplayCaption
End Sub

Private Sub opt686_Click()


' assign a value to the first string variable
strComputer = "Pentium Pro"
' call the subroutine
Call DisplayCaption
End Sub

Private Sub optWin95_Click()


' assign a value to the second string variable
strSystem = "Windows 95"
' call the subroutine
Call DisplayCaption
End Sub

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Private Sub optWinNT_Click()
' assign a value to the second string variable
strSystem = "Windows NT"
' call the subroutine
Call DisplayCaption
End Sub

Figure 3a

The fourth form is check.frm. It contains two check boxes, one text box and two
command buttons and one label. They are captioned and positioned as shown in the
figure 4. The codes are entered in the code window as shown in the figure 4a.

Private Sub chkBold_Click()


' The Click event occurs when the check box changes state.
' Value property indicates the new state of the check box.
If chkBold.Value = 1 Then ' If checked.
txtDisplay.FontBold = True
Else ' If not checked.
txtDisplay.FontBold = False
End If
End Sub

Private Sub chkItalic_Click()


' The Click event occurs when the check box changes state.
' Value property indicates the new state of the check box.
If chkItalic.Value = 1 Then ' If checked.
txtDisplay.FontItalic = True
Else ' If not checked.
txtDisplay.FontItalic = False
End If
End Sub

Private Sub cmdClose_Click()


Unload Me ' Unload this form.
End Sub

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4a

Save the Project and run the same and examine the output obtained in each of the
forms.

x------x

Visual Basic-6
9. Creating a User Defined ActiveX Control

So far we have been using the ActiveX Controls which come along with the
Professional Edition of VB-6. We have said that the greatest power if VB-6 is its
capacity to create user defined ActiveX controls which can be used for building complex
applications. We have also pointed out that one can visualize a scenario, when every
complex application will be encapsuled in a single ActiveX control. In this lesson we
will see how one can go about building one’s own ActiveX control.

Building a Picture ActiveX Control:

The Picture ActiveX Control is intended to print pictures in a Picture box selecting
bmp or ico or gif files by searching the directories.

1. Open the VB-IDE.

2. Click ‘New Project’ from the file menu to open the New Project Dialog Box as
shown in the figure 1. Doubleclick on the ActiveX Control icon. You will get a
user control form named as usercontrol1. Open the property window of the form and
change its name property as .rform1 and then change the name property of the project
as rproj. Drag a picture box, dir , drive and file controls from the Toolbox, size them
and position them as shown in the figure 2.Open the code window and enter the codes
as shown in the figure 2a.

Private Sub File1_DblClick()


Picture1.Picture = LoadPicture(File1.Path & "\" & File1.filename)
End Sub

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Private Sub Dir1_Change()
File1.Path = Dir1.Path
End Sub

Private Sub Drive1_Change()


Dir1.Path = Drive1.Drive
End Sub

Figure 2a

3. Save the form and the project one by one with the same names you have given before.
The control form is stored as rform1.ctl and the project is stored as rproj.vbp. Click
‘Make rproj.ocx’ from the file menu. Save the ocx file as rproj. Now you have
created an ActiveX control by name rproj.rform This ActiveX control cannot be
used directly. It has to be placed in a container before we make use of the ActiveX
control.

Containers for placing ActiveX Controls:

ActiveX controls can be placed in any of the following four containers.

1. VB Design Form
2. ActiveX Control Pad
3. Microsoft Excel 97
4. Microsoft Word 97
5. ActiveX Control Test Container

1. ActiveX control placed in VB Design Form:

Open the Standard EXE Design Form. At the bottom of the Toolbox, you must be
able to find the icon by name rform for the new ActiveX control you have created.. If
you don’t find it, open the component menu by clicking component from project menu.
You will find the ocx file by name rproj as shown in the figure 3. Select it and click OK.
The icon by name rform will appear at the bottom of the toolbox. Drag the new ActiveX
control in the design form and size it so that all its components are clearly visible as
shown in the figure 4. Save the form as rrform and the project as rrproj. Select start
from the Run menu. Now you can vary the drive, the directory and the files in the Run
Mode.. Select a gif file and double click it. You will get the corresponding image
loaded in the picture box as shown in the figure 5.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 3

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 5

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


2. ActiveX Control placed in ActiveX Control Pad:

Open the Microsoft ActiveX Control Pad from the Program List. It will present a
blank HTML form . Select ‘insert’ from the Edit menu. You will get the list of
ActiveX Controls in the alphabetical order as shown in the figure 6. Click the control
rproj.rform. The control window and the property window will appear on the screen as
shown in the figure 7. Close the two windows. You will find the code for the ActiveX
control written between two object tags as shown in the figure 8. Save the html file as
rr.htm in the desktop directory. Close the ActiveX control pad. Click the icon rr which
you see in the opening window. Immediately Internet Explorer will be opened and give
a warning message ‘An ActiveX object on this page may be unsafe. Do you want to
allow it to be initialize and be accessed by script’. Press Yes. The ActiveX control in
dynamic mode will be displayed in it. You can now play with the directories and files
and display an image in the picture box as shown in the figure 9.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 6

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 7

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 8

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 9

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


3. Placing the ActiveX Control in the Microsoft Excel 97:

. Open Microsoft Excel Worksheet. From the View menu select Toolbars item. Then
select Control Toolbox option. The control box will appear, floating over the
spreadsheet. At the bottom of the control box, you will see an icon with a crossed
hammer and wrench. If you click this icon the ActiveX component Menu will appear.
Select the item rproj.rform. The menu will disappear and the cursor becomes a crosshair
and will allow you to draw the ActiveX control on the Spreadsheet. Exit from the design
mode by clicking on the Design Mode Icon which appears in the beginning of the control
box. The ActiveX control becomes dynamic. You can select a gif file and display it in
the picture box as shown in the figure 10

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 10

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


4. Placing the ActiveX control in the Microsoft Word 97 Document:

Open Microsoft Word and open a blank document. From the view menu select
Toolbars and then Control Toolbox. You will get a menu of ActiveX controls. Select
the Control ‘rproj.rform’. Exit Design mode by clicking on the design mode icon from
the tool box. The ActiveX control form appears in the dynamic mode. Now you can
change the directories, drives and files. Select a bmp file or gif file and display it as
shown in the figure 11

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 11

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


6. Microsoft ActiveX Control Test Container:

A new utility called the ActiveX Control Test Container has been included in VB-6.
This tool allows you to load an ActiveX control that you have created in order to test.
From the start up menu select Microsoft Visual studio->Microsoft Visual Studio 6.0
Tools->ActiveX Control Test Container as shown in the figure 12. You will be
presented with a blank ActiveX Test Container window as shown in the figure 13.
Select Edit->Insert New Control. You will get a list of ActiveX Controls as shown
in the figure 14. Select rproj.rform. The ActiveX control becomes active and you
can select a gif file for display as shown in the figure 15. You can insert the
Calendar Control and you will find that the calendar becomes dynamic.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 12

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 13

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 14

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 15

x-------------------------------------------------x

Visual Basic-6
10. Project using ActiveX DLL

What is DLL?

A dynamic-link library(DLL) is a set of procedures that are external to your


application, and can be called from your application. DLLs are not bound to your
executable file, and so they can be linked to your application at run time, instead of being
loaded at compile time. The libraries can be updated independently of the application
and multiple applications can share a single DLL.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Advantages of using DLLs:

DLLs can accomplish tasks that are difficult with VB.


DLLS will run faster than VB code resulting in improved performance.
DLLs can be updated independently of the application.

Declaring a DLL Procedure:

DLL procedures reside in files that are external to your VB application and so you
must declare a procedure before you call it. Declaring a procedure provides VB with the
information it needs to find and run the procedure you want to use.

Steps used in creating an ActiveX DLL Project:

1. Open the VB IDE.


2. Select New Project from the File Menu. You will get the Project window as shown
in the figure 1. Select the icon named ActiveX DLL.
3. Add a form to the Project using the Add Form window shown in the figure 2. This
window is obtained by selecting Add Form from the Project Menu.. Change its name
property as chartfrm.
4. Change the name property of the project as chartprj.
5. Change the name property of the class modules as chartcls.
6. Drag a MSChart control in the form and size it appropriately as shown in the figure 3.
7. Save the modules as chartcls, the form as chartfrm and the project as chartprj. These
names must appear as shown in the figure 3.
8. Now you have to write the DLL procedure for drawing a chart. Double click the
class module. You will get the general declaration window.. Select Add procedure
item from the Tools menu. You will get the Procedure heading and the ending tags.
Write the body of the procedure. The dll procedure is entered as in the figure 3a.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 3

Public Sub setchart(ByVal data1, ByVal noofrows, ByVal noofcols)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Dim i, j, k As Integer
k = 1995
chartfrm.MSChart1.RowCount = noofrows
chartfrm.MSChart1.ColumnCount = noofcols
chartfrm.MSChart1.chartType = VtChChartType2dBar
For i = 1 To noofrows
For j = 1 To noofcols
chartfrm.MSChart1.Row = 1
chartfrm.MSChart1.Column = j
chartfrm.MSChart1.RowLabel = k
chartfrm.MSChart1.Data = data1(i, j)
Next j
k=k+1
Next i
chartfrm.Show
End Sub

Figure 3a

Save the project. Select ‘Make chartproj.dll’ from the file menu thereby saving the
complete DLL procedure.file. This DLL file must be referenced by selecting the DLL
project from the reference library window. Select references from the project window.
You will get the list of reference libraries in the alphabetical order as shown in the figure
4. Select the file chartprj.

In order to call the DLL procedure start the Standard Exe project. Drag a command
button in the Design window. Change its caption and name as calldll and locate it as
shown in the figure 5. Open the code window for the command button and enter the
code for calling the DLL as shown in the figure 5a. Save the form and the project as
dllform aand dllproj respectively. Run the project. You will have to enter the data for
the number of rows, number of columns , values for the rows and columns. Finally you
will get the bar chart for the supplied data as shown in the figure 6.

Private Sub Command1_Click()


Dim r, c
Dim data22(1 To 10, 1 To 10)
r = Val(InputBox("enter the number of rows"))
c = Val(InputBox("enter the number of columns"))
For i = 1 To r
For j = 1 To c
data22(i, j) = Val(InputBox("enter value for row " & i & "column " & j))
Next j
Next i
Dim obj As chartprj.chartcls
Set obj = New chartcls
Call obj.setchart(data22, r, c)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


End Sub

Figure 5a

Figure 4

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 5

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 6

x----------------------------------------------------x

Visual Basic-6
11. Creating ActiveX Documents

So far we have been looking at the VB projects in its own environment. With the
growth of the internet it has become necessary to make every project Browser enabled.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


It is possible to make every VB Standard EXE project Browser enabled by converting to
what is named as ActiveX Document Project.

Creating the ActiveX Document Project:

Open the VB IDE and select New from the File menu. The Project window Dialog
appears as shown in the figure 1.

Now select ActiveX Document DLL icon. Immediately the user document form is
opened. Select the ‘project’ item and change its name as ‘demodocproj’ by opening its
properties window. In a similar way select the ‘form’ item and change its name as
‘demodocform’. Now you can create any project in the form as we do for the Standard
EXE project. In this example we create a project to convert a temperature from
Fahrenheit to Centigrade and vice versa. Drag two labels , one text box and two
command buttons, size them, caption them and position them as shown in the figure 2.

Open the code window and enter the codes as shown in the figure 2a. Save the
form and the project separately the form is saved as demodocform.dob and the
project is saved as demodocproject.vbp.

Private Sub Command1_Click()


Text1.Text = ctof(CDbl(Text1.Text))
End Sub

Private Sub Command2_Click()


Text1.Text = ftoc(CDbl(Text1.Text))
End Sub

Function ftoc(temp As Double) As Double


ftoc = (temp - 32) * 5 / 9
End Function

Function ctof(temp As Double) As Double


ctof = temp * (9 / 5) + 32
End Function

Figure 2a

Then select ‘Make demodocproj.DLL’ from the File menu. This will create a
document file named demodocform.vbd. Open the Internet Explorer and view the
file ‘demodocform.vbd’. The project appears as shown in the figure 3 and you can
interact with it as you do with any Standard EXE project.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
Figure 1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 3

Creating the ActiveX Document from an existing Standard ActiveX EXE Project:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Suppose you create a Standard EXE project to draw a color gradient. The design
window of the color gradient project looks as in the figure 4. It contains one Picture box
control and three command button controls as shown in the figure 4. Open the code
window and enter the codes as shown in the figure 4a. Save and run the project and see
that the color gradient works properly. You can experiment with different starting and
ending colors for the gradient by changing the values of the variables color1 and color2.

Private Sub Command1_Click()


Dim newcolor As Long
Dim ipixel, pwidth As Integer
Dim redinc, greeninc, blueinc As Single
Dim color1 As Long, color2 As Long
color1 = RGB(255, 255, 0)
color2 = RGB(0, 0, 0)
startred = getred(color1)
endred = getred(color2)
startgreen = getgreen(color1)
endgreen = getgreen(color2)
startblue = getblue(color1)
endblue = getblue(color2)
pwidth = Picture1.ScaleWidth
redinc = (endred - startred) / pwidth
greeninc = (endgreen - startgreen) / pwidth
blueinc = (endblue - startblue) / pwidth
For ipixel = 0 To pwidth - 1
newcolor = RGB(startred + redinc * ipixel, startgreen + greeninc * ipixel, startblue +
blueinc * ipixel)
Picture1.Line (ipixel, 0)-(ipixel, Picture1.Height - 1), newcolor
Next
End Sub

Function getred(colorval As Long) As Integer


getred = colorval Mod 256
End Function
Function getgreen(colorval As Long) As Integer
tgreen = ((colorval And &HFF00FF) / 256&)
End Function
Function getblue(colorval As Long) As Integer
getblue = (colorval And &HFF0000) / (256& * 256&)
End Function

Figure 4a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


After creating the above Standard EXE project, we will use the Wizard to convert this
to document file. Select ‘ActiveX Document Migration Wizard’ from the ‘Add-Ins’
menu. Check whether this menu item is available in the ADD-Ins menu. If not you
have get it from ADD-In Manager. You will get the opening screen as shown in the
figure 5. It is only an informative screen. Then click ‘next’. You will get the second
screen called the Form Selection screen as shown in the figure 6. Select the form and
click ‘next’. You will get the options screen as shown in the figure 7. Click the two
options, ‘comment out invalid code’ and convert to ActiveX EXE’. Then click next.
You will get the finish screen as shown in the figure 8. When you click finish you will
get the message box that the document is created. Now select ‘make gradproj.exe. from
the file menu. This will create the document file docform1.vbd. You will notice that the
document project does not accept the End command given in the exit button. You can
remove that before you start the wizard. Open the Internet Explorer window and view
the docform1.vbd file. You will find the gradient project working in this screen as
shown in the figure 9.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 5

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 6

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 7

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 8

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 9

Establishing Hyperlinks between two VB documents:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Create two VB documents rrdform1.vbd and rrdform2.vbd as shown in the figures 10
and 11 respy. Each document contains a text box and a command button. They are
captioned as shown in the figures. The code for each of the buttons must be entered in
their respective code windows as shown in the figures 10a and 11a. Save the files.
Open the first file rrdform1.vbd in the Internet Explorer. When you click the button, the
second file is opened. When you click the button in the second file the first file is
opened. Hyperlinking documents enables one to navigate through different documents
very quickly.

Private Sub Command1_Click()


UserDocument.Hyperlink.NavigateTo "c:\vbproj\rrdform2.vbd"
End Sub

Figure 10a

Private Sub Command1_Click()


UserDocument.Hyperlink.NavigateTo "c:\vbproj\rrdform1.vbd"
End Sub

Figure 11a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 10

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 11

x------------------------------------------------------x

Visual Basic-6

12. Database Projects(1)


Aim of the Project:

The aim of this project is to create a database using the Visual Data Manager, use the
DBGrid ActiveX control and display the contents of the selected table in the DBGrid
box.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Creating a Database using Visual Data Manager:

We start from the opening window of Visual Basic-5. Select Visual Data Manager
from the Add-Ins menu. A blank Visual Data Manager window appears on the screen as
shown in the figure 1.

Select New from the File Menu and then select Microsoft Access->version 2 MDB.
Select a folder to save the MDB file and type the database filename as payroll.mdb and
click OK. The payroll.mdb window will appear on the screen as shown in the figure 2.

Creating the Structure of the Database:

In order to create a structure for a table by name employee, select ‘properties’ in the
database window and right-click it. Select the New Table Option. The Table Structure
Window appears on the screen as shown in the figure 3.

Enter the table name as ‘employee’. Now click ‘Add Field’ item. You will get the
field entry dialog window as shown in the figure 4.

Enter the first field name as ‘empno’. Select the Type as Text and size as 10. Then
click OK. You will get back to the Table Structure window. Repeat the process of
adding field for three more items, namely empname, dept and salary. For salary enter
the data type as Currency. The final table structure window with four fields will appear
as shown in the figure 5.

To finish the table creation, click ‘Build the Table Button’. Now the Table structure
creation is over. Next we can optionally add indexes to the fields.

Adding an Index:

We will set the empno field as the primary and unique field. Right-click on the
employee table and select the ‘Design’ option from the menu. Click the ‘Add Index’
button. A window titled ‘Add Index to employee’ will appear as shown in the figure 6.

Enter empno into the Name field. Select empno from the “available Fields’ list box.
Check the Primary and the Unique boxes. Click OK to add the primary key index. Click
close. The Database window will display the fields and the indexed field as in the
figure 7.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Adding Data:

Right-click on the employee table, but this time select ‘Open’. You will get the data
entry window as shown in the figure 8.

To add a record click Add and then fill the four fields with appropriate data. When you
have filled in the data for the first record, click ‘Update’ to save the first record and clear
the fields for the next set of values. Click Add again to add the next record. Continue
until you have created some 5 records. Now you have created a sample database for
further experimentation.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 3

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 5

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 6

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 7

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 8

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Project using the DBGrid Control to display the Database Table:

Let us now consider a project to display the database table we created earlier in a
DBGrid Box.

Controls used in this Project:

In this example project we are going to use the following Controls.

1. DB Grid Control (1)


2. Data Control (1)

Start from the opening Design Window, drag the above controls in the form, size
them and locate them in the form as shown in the figure 9. The DBGrid control is
bound to the database control by setting its data source property as ‘Data1’ The Data
control is connected to the database by making the Database name property as ‘payroll’
and the Record Source property as ‘employee’. You must give the database name along
with the directory structure. There is no coding for this project. Save and run the
project. The database table is displayed in the DBGrid box as shown in the figure 10.
Suppose you want to view only selected records based on some criteria, enter the criteria
as the Record Source Property of the Data Control as:

Select * from employee where salary < 10000 and salary > 5000

The output will appear as shown in the figure 11.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 9

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 10

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 11

x------------------------------------------------------------------------------x

Visual Basic-6
13. Database Projects(2)
DataBases and Database Management Systems:

Visual Basic provides tools for creating and accessing databases. The two major
tools are

1. The Data Control


2. The Data Access Object

In this lesson we will consider the following projects;

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


1. Making SQL Queries in Databases using Data Control
2. Binding Data Controls with Text Boxes
3. Accessing DAO Objects in Debug Window

The Data control gives access to the Database without any programming, since it is a
powerful ActiveX Control. The Data Access Object is a structure of objects for
accessing the database through programming.

We know that a Database is a grouping of related information organized for easy


retrieval and processing. The actual data are stored in tables in a row-column format. A
row is called a record.

Recordsets are objects that represent collections of records from one or more tables.
Recordsets are the equivalent of variables in regular programming. You can access the
tables of a database only by manipulating the Recordset objects. A Recordset is a view
of some data in the database, selected from the database according to user-specified
criteria. There are three types of Recordsets, namely

1. DynaSets which are updatable views of data


2. SnapShots which are static(read-only) views of data
3. Tables, which are direct views of tables.

1. SQL Queries using Data Control:

Drag a DB grid Control, a Data Control, a label control, two Command buttons, a
Common Dialog Control and a Textbox Control on the form, size them, and position
them on the form as shown in the figure 1 . Set the visible property of the Data Control
false so that it will not be visible at run time. Set the Name property of the Textbox as
txtsql, multiline property as true and scrollbars property as 2-Vertical. Caption the
command buttons as in the figure. Open the code window for the two command buttons
and enter the code as shown in the figure 1a. Save and run the project. On clicking the
open database button, ‘file open dialog box’ appears. Select the database file. The
name of the database file appears on the label box at the top. Then enter the sql query in
the text box and press the execute button. The result appears on the DBGrid control box.
A typical example is shown in the figure 2.

Private Sub Command1_Click()


On Error GoTo nodatabase
CommonDialog1.CancelError = True
CommonDialog1.Filter = "databases|*.MDB"
CommonDialog1.ShowOpen
Data1.DatabaseName = CommonDialog1.filename
Data1.Refresh

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


If Err = 0 Then
Label1.Caption = CommonDialog1.filename
Else
MsgBox Err.Description
End If
nodatabase:
On Error GoTo 0
End Sub

Private Sub Command2_Click()


On Error GoTo sqlerror
Data1.RecordSource = txtsql
Data1.Refresh
Exit Sub
sqlerror:
MsgBox Err.Description
End Sub

Figure 1a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2

2. Binding Data Control with Text Boxes:

In the last example the Data Control was bound to the DBGrid control so that the
output was displayed in the DBGrid box. This time we will bind the Data control with
text boxes binding each field of the database with a text box. In addition we will add
facilities for add, delete, edit, find and seek methods to operate on the database. Drag a
Data Control, four label boxes, four text boxes and thirteen command buttons, size them,

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


caption them and position them as shown in the figure 3. Set the Database Name
property by actual browsing and the record source property for the Data control object.
For each of the text box set the data source property as D1 and data field property as the
name of the field which it is to display. It may be noted that the seek method will work
only with Table type recordset and so set the Recordset type property of the data control
as ‘0-Table’. For working with the Find method, set the Recordset type property as 1-
Dynaset. Open the code window for the different command buttons and enter the codes
as shown in the figure 3a. Run the project and check the function of each command
button. A typical output is shown in the figure 4.

Private Sub add_Click()


Data1.Recordset.AddNew
Text1.SetFocus
End Sub

Private Sub delete_Click()


Data1.Recordset.delete
End Sub
Private Sub edit_Click()
Data1.Recordset.edit
End Sub

Private Sub exit_Click()


Unload Me
End Sub

Private Sub fieldcount_Click()


MsgBox "Number of fields " & Data1.Recordset.Fields.Count
End Sub

Private Sub find_Click()


Dim c As String
c = InputBox("enter the empno whose record is required")
Data1.Recordset.FindFirst "empno =" & "'" & c & "'"
End Sub

Private Sub movefirst_Click()


Data1.Recordset.movefirst
End Sub

Private Sub movelast_Click()


Data1.Recordset.movelast
End Sub

Private Sub movenext_Click()

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Data1.Recordset.movenext
If Data1.Recordset.EOF Then
MsgBox "you are on the last record"
Data1.Recordset.movelast
End If
End Sub

Private Sub moveprevious_Click()


Data1.Recordset.moveprevious
If Data1.Recordset.BOF Then
MsgBox "you are on the first record"
Data1.Recordset.movefirst
End If
End Sub

Private Sub reccount_Click()


Data1.Recordset.movelast
MsgBox "Number of Records " & Data1.Recordset.RecordCount
End Sub

Private Sub save_Click()


Data1.Recordset.Update
End Sub

Private Sub seek_Click()


Dim c
c = InputBox("enter the empno whose record is required")
Data1.Recordset.Index = "empno"
Data1.Recordset.seek "=", c
End Sub
Figure 3a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 3

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


3. Accessing Databases through Data Access Objects(DAOs):

DAO is the object oriented interface to the Microsoft Jet database engine. DAO
onkects enable you to access and manipulate data programmatically in local and remote
databases. You use DAO to manage databases with the help of their structures. The
DAO objects are organised in a hierarchial fashion starting from the DBEngine as shown
below.

DBEngine
Workspace
Database
TableDef QueryDef RecordSet
Field Field
Parameters

The Workspace object defines a session for the user. When your application starts,
the Jet engine creates a default workspace object. You can open additional workspaces
if required and each workspace has a userID and a password associated with it.

You must start with declaring an object variable db for the Database and assign it to a
particular database using the Set statement as

Dim db As Database
Set db = OpenDatabase(“payrollo.mdb”)

A Recordset object contains a set of records from the database. You must create the
Recordset by declaring a variable for the Recordset object and then assigning it to the
table as

Dim rs As Recordset
Set rs = db.OpenRecordSet(“employee”, dbOpenTable)

The type of recordset can be either dbOpenTable or dbOpenDynaset or dbOpenSnapShot.


There are no bound controls for the DAO objects and so you have to copy data from a
Recordset to a textbox one by one. A specifi field, say empno is assigned to a text box
as

Text1.text = rs(“empno”)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The DAO objects cannot be bound to Grid Controls. So we will use the Debug
window to display the database table. Displaying the individual Records in Text Boxes
can be done as in the previous example.

Start with the Standard EXE Project Form. Before starting to work with DAO, you
must first make the DAO object library available by making a reference to it. Select
references from the project menu and select the DAO Object Library version 3.5 as
shown in the figure 5. .Drag a Command button to the design window form, and
caption it as shown in the figure 6. Enter the code in the button’s code window as
shown in the figure 6a. Save and run the project. The output in the debug window
appears as shown in the figure 7.

Private Sub display()


Dim db As Database
Dim rs As Recordset
Set db = OpenDatabase("\vbproj\payroll.mdb")
Set rs = db.OpenRecordset("employee", dbOpenTable)
Do While Not rs.EOF
Debug.Print rs(0), rs(1), rs(2), rs(3)
rs.MoveNext
Loop
rs.Close
End Sub

Private Sub Command1_Click()


Call display
End Sub

Figure 6a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 5

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 6

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 7

x------------------------------------------x

Visual Basic-6
14. Database Projects(3)

In this lesson we will consider some projects using DAOs, ODBC and ADOs..

1. Creating a Database and a Table:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The dbEngine object is used to create the workspace for the database file. The
TableDef object is used to create the table. Drag three command buttons in the form,
caption them, size them and position them as shown in the figure 1. Open the code
window and enter the codes as shown in the figure 1a. Data are inserted in the table by
the sql command ‘insert’. The syntax of the Insert statement is:
INSERT INTO AUTHOR VALUES(AUID, ANAME) VALUES(24, ‘KKKK’)
Any number of records can be added, but each time the enter data button is pressed.

Save and run the project and see how the three commands work. You will get an error
message if you try to create a database which is already present. You can see the
database table in the Immediate window by pressing the display button. In order to see
the database table in the DBGrid, open another form. Place a data control and a DBGrid
control box. Bind the data control to the database ‘publisher’ and the Record Source to
‘author’. DBGrid is bound to ‘Data1’.. and The form2 is shown in the figure 2 and
the output is shown in the figure 3. Notice the two forms are not related in the program
and so is separately run. To run the form2, open the properties dialog table by pressing
the properties item from the project menu and select form2 for the startup object from the
dropdown list.

Dim ws As Workspace
Dim db As Database
Dim td As TableDef

Private Sub Command1_Click()


'program for creating a database
Dim i As Integer
Dim flds(2) As Field
Set ws = DBEngine.Workspaces(0)
Set db = ws.CreateDatabase("c:\vbproj\publisher", dbLangGeneral, dbVersion25)
Set td = db.CreateTableDef("author")
Set flds(0) = td.CreateField("auid", dbLong)
Set flds(1) = td.CreateField("aname", dbText)
flds(1).Size = 10
td.Fields.Append flds(0)
td.Fields.Append flds(1)
db.TableDefs.Append td
MsgBox ("database created")
End Sub

Private Sub Command2_Click()


'program for inserting data
Set db = OpenDatabase("c:\vbproj\publisher")
Set rs = db.OpenRecordset("author", dbOpenTable)
db.Execute SQLTEXT, dbFailOnError
End Sub
Private Sub Command3_Click()

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Set db = OpenDatabase("c:\vbproj\publisher")
Set rs = db.OpenRecordset("author", dbOpenTable)
Do While Not rs.EOF
Debug.Print rs(0), rs(1)
rs.MoveNext
Loop
rs.Close
End Sub

Figure 1a

Figure 1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
Figure 2

Figure3

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


2. Project using DAO object TableDef:

In this project data are added to the table using text boxes and the Addnew method.
The input form appears as shown in the figure 4. Enter the code in the code window as
shown in the figure 4a. Save and run the project. The output window will look as in the
figure 5. Clicking the display button will update the debug window and clicking the
refresh button will update the DBGrid window.

Dim db As Database
Dim rs As Recordset
Private Sub Command1_Click()
Set db = OpenDatabase("d:\rr2\college")
Set rs = db.OpenRecordset("author", dbOpenTable)
rs.AddNew
rs("authorid") = Text1.Text
rs("authorname") = Text2.Text
rs.Update
rs.Close
End Sub

Private Sub Command2_Click()


Set db = OpenDatabase("d:\rr2\college")
Set rs = db.OpenRecordset("author", dbOpenTable)
Do While Not rs.EOF
Debug.Print rs(0), rs(1)
rs.MoveNext
Loop
rs.Close

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


End Sub

Private Sub Command3_Click()


Set db = OpenDatabase("d:\rr2\college")
Set rs = db.OpenRecordset("author", dbOpenTable)
rs.MoveLast
rs.Delete
rs.Close
End Sub

Private Sub Command4_Click()


Data1.Refresh
End Sub

Figure 4a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 5

3. Project using QueryDef Object:

In this project we make use of the QueryDef object to execute a stored sql query.
The input form contains only a command button. Enter the code as shown in the figure
6a. The output window appears as shown in the figure 6.

Dim dbspayroll As Database

Sub CreateQueryDefX()
Dim qdfTemp As QueryDef
Set dbspayroll = OpenDatabase("c:\vbproj\payroll.mdb")
With dbspayroll

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Set qdfTemp = .CreateQueryDef("", "select * from Employee where salary > 7000")
GetrstTemp qdfTemp
.Close
End With
End Sub

Function GetrstTemp(qdfTemp As QueryDef)


Dim rsttemp As Recordset
With qdfTemp
Debug.Print .Name
Debug.Print " " & .SQL
Set rsttemp = .OpenRecordset(dbOpenSnapshot)
Do While Not rsttemp.EOF
Debug.Print rsttemp(0), rsttemp(1), rsttemp(2), rsttemp(3)
rsttemp.MoveNext
Loop
With rsttemp
.MoveLast
Debug.Print "number of records = " & .RecordCount
.Close
End With
End With
End Function

Private Sub Command1_Click()


Call CreateQueryDefX
End Sub

Figure 6a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 6

4. Project for querying from multiple tables using Querydef:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Suppose you have two tables named student and course in a database college as
shown in the figure 7 and 8. You want to make a query involving data from both
tables and print them in the sorted order of the student numbers. Enter the code as
shown in the figure 7a. The output of the query appears as shown in the figure 9.

Dim dbscollege As Database

Sub CreateQueryDefX()
Dim qdfTemp As QueryDef
Set dbscollege = OpenDatabase("d:\rr2\college.mdb")
With dbscollege
Set qdfTemp = .CreateQueryDef("", "select student.sno, student.sname, student.major,
result.cno, result.grade from student, result where student.sno = result.sno order by
student.sno")
GetrstTemp qdfTemp
.Close
End With
End Sub

Function GetrstTemp(qdfTemp As QueryDef)


Dim rsttemp As Recordset
With qdfTemp
Debug.Print .Name
Debug.Print " " & .SQL
Set rsttemp = .OpenRecordset(dbOpenDynaset)
Do While Not rsttemp.EOF
Debug.Print rsttemp(0), rsttemp(1), rsttemp(2), rsttemp(3), rsttemp(4)
rsttemp.MoveNext
Loop
With rsttemp
.MoveLast
Debug.Print "number of records = " & .RecordCount
.Close
End With
End With
End Function

Private Sub Command1_Click()


Call CreateQueryDefX
End Sub

Figure 7a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 7

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 8

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 9

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


.
Data Access through ODBC:

A Data Access Object can be connected by a ODBC driver and data objects can be
accessed and printed in the Debug window. First you set up a form with a single
command button as shown in the figure 10.. In the code window of the command button
enter the code as shown in the figure 10a. Save and run the project. You will get the
output for all the SQL queries entered in the program. You can modify the program so
as to enter the queries from an input text box at the time of execution. A typical output
is shown in the figure 11.

Private Sub Command1_Click()


Dim wRKodbc As Workspace
Dim conpubs As Connection
Dim D As Database
Dim r As Recordset
Set wRKodbc = CreateWorkspace("NewODBCWorkspace1", _
"admin", "", dbUseODBC)

'Set conpubs = wRKodbc.OpenConnection("Connection1", dbDriverPrompt)


Set conpubs = wRKodbc.OpenConnection("Connection2", , , _
"ODBC;DATABASE=PAYROLL;UID=ADMIN;PWD=SYSTEM;DSN=D1")
Debug.Print ""
Set r = conpubs.OpenRecordset("SELECT * FROM EMPLOYEE")
Do While Not r.EOF
Debug.Print r(0), r(1), r(2), r(3)
r.MoveNext
Loop
End Sub

Figure 10a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure10

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure11

x---------------------------------------------------x
.

Visual Basic-6
15. Database Projects(4)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


In this lesson we will consider Database processing using the ActiveX Data Objects or
ADOs as they are called which have been newly added in VB6. We start with a database
‘publisher’ and the table ‘author’ as shown in the figure 1. The aim is to access and
manipulate this database using the ADO objects.

What is ADO?.

ADO is a Data Access Tool similar to DAO but with more powerful and advanced
features for manipulation and Reporting. With ADO VB application sees three objects:

1. A Connection Object, which establishes a connection to the database, be it a local file


or a remote SQL server.

2. A Command Object, which executes commands against the database.

3. A Record Set Object, which holds the records retrieved from the database or the
records to be updated on the database.

Creating a Database Project using ADO:

Select ‘New Project’ from the File Menu.


You will get the Project Menu as shown in the figure 2. Select the Data Project Icon and
click OK. You will get the form window as shown in the figure 3. In the Project
Explorer window, VB displays a new Form as usual, and two ActiveX Designers.
Database applications rely on two basic components.:

• One or more Data Environment Component(s).


• One or more DataReport Component(s).

The DataEnvironment component lets you design a connection to a database and retrieve
the desired records. The DataReport component lets you design reports and use them
within your applications. Both components are based on visual tools and they don’t
require programming.

The Data projects Toolbox contains a number of ActiveX controls.

• The ADODC (ADO Data Control), which is similar to the Data Control.
• TheDataList and DataCombo controls, which are data-bound versions of the ListBox
and ComboBox controls and they work with ADO control and not with Data
Control.
• The MSHFlexGrid control, which is a hierarchial Grid control and is meant to be
populated
• automatically by the DataEnvironment Designer.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 3

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Double-click the DataEnvironment Object in the Project Explorer window to open the
DataEnvironment window as shown in the figure 4. The DataEnvironment of the
application consists of a Connection object(the Connection1 object) and one or more
Command Objects. The Command Object is empty, but this is where the Command
Object we will create later will be stored.
Right-click the Connection1 object, and from the shortcut menu, select properties to open
the Data Link Properties window. You use the tabs in this window as shown in the
figure 5 to specify the database to which you want to connect. In the Provider5 tab,
select the driver between your application and the database. Select the Microsoft jet 3.51
OLE DB Provider since this is the simplest provider that can connect your application
directly to Microsoft Access database.
Now select the Connection tab. Click the button with the ellipsis and locate the database
‘publisher’ which has been created earlier. Click the ’Test Connection’ to make sure that
the connection works. You will get a message box as in the figure 6. Select the
‘Advanced tab’ to specify how the database will be opened. Accept the default option,
‘Share Deny None’ Select ‘ALL’ tab to display the settings you specified as seen in the
figure 7. Click OK to return to the Environment window.

We have established a connection to the database and made sure it works. Now let us
create a Command Object to request some records. We want to display the records of
the author table on the form.

Right-click the Command1 object and from the popup menu select ‘Properties’ to open
the Command1 Properties Window as shown in the figure 8. In the General tab set the
Command Object’s name as ‘author’ and its connection to Connection1. In the database
object box select ‘table’. If you don’t see the item ‘table’ click ‘Apply’ and you will get
the table item. Click OK to return to the Data Environment window.

Click the + sign in front of the Command1 object. You will get the display of all the
fields in the author table.

Switch to the projects form(Form1). With the Form and the Data Environment window
visible on the screen, drag the Command1 object and drop it in the form. VB will create
as many pairs of label and Text Box Controls as needed to display all the fields of the
Command object as shown in the figure 9. Save each of the forms and the project
separately. Run the project. You will see the fields of the first record displayed on the
text boxes as shown in the figure 10.
This form lacks navigation facilities and for this we have to write codes.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
Figure 4

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 5

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 6

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 7

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 8

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 9

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 10

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Programming Navigation Buttons:

Place four command buttons in the Form and caption them as shown in the figure 11.
For each of the command buttons enter the code in the code window as shown in the
figure 12a.

Private Sub Command1_Click()


DataEnvironment1.rsCommand1.MoveFirst
End Sub

Private Sub Command2_Click()


If DataEnvironment1.rsCommand1.BOF Then
Beep
Else
DataEnvironment1.rsCommand1.MovePrevious
If DataEnvironment1.rsCommand1.BOF Then
DataEnvironment1.rsCommand1.MoveFirst
End If
End If
End Sub

Private Sub Command3_Click()


If DataEnvironment1.rsCommand1.EOF Then
Beep
Else
DataEnvironment1.rsCommand1.MoveNext
If DataEnvironment1.rsCommand1.EOF Then
DataEnvironment1.rsCommand1.MoveLast
End If
End If
End Sub

Private Sub Command4_Click()


DataEnvironment1.rsCommand1.MoveLast
End Sub

Figure 12a.

Save and run the project. You will get the run mode window as shown in the figure 13.
You will now be able to navigate the table using the buttons.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 11

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 13

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 14

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


ADO Data Control:

VB-6 has included a new Data Control called the ADODC which is somewhat similar
to the Data Control in VB-5. The ADODC and DataGrid Controls are automatically
included in the Tool box when you select Data Object from the New Project Menu.
Double-click the item frmDataEnv in the Project Explorer window for displaying the
form on the screen. Place a DataGrid Control, a ADODC control , four text boxes and
four labels in the form, caption and locate them as shown in the figure 15. Now you
have to bind the ADODC control with the Data Grid as well as the four text boxes. Set
the DataSource Property and the DataField Property of the Text boxes as shown below.
Control Name DataSource Property DataField Property

Text1 Adodc1 auid


Text2 Adodc1 aname
Text3 Adodc1 adept
Text4 Adodc1 salary

For binding the DataGrid with Adodc1, set the DataSource property of the grid as
Adodc1.
Now you must establish connection to Adodc1 with the Database.
Right-click the Adodc1 control and select the item Properties. You will get the
Properties window as shown in the figure 16.
Enter the user source name as DEMO. Under the General Tab.
Now go to Resources Tab and enter ‘author’ in the box having the label ‘Table or Stored
Procedure’ Enter the value for the Command Type box as ‘2-adCMdTable’ as shown in
the figure 17. Click OK. The connection is now established between the Adodc1 and
the database table ‘author’. Save and run the project. You will get the output window
as shown in the figure 18. Now you can play with the navigation arrows in the Adodc1
and see the changes in the text boxes and the DataGrid.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html
Figure 15

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 16

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 17

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 18

x---------------------------------------------x

Visual Basic-6

16. Database Projects(5)


In this lesson we will see how we can create a ODBC Data Source and use it with
ADO controls.

Creating ODBC Data Source:

In the last lesson we used DEMO as the name of the ODBC Data Source. Let us see
how another Data Source by name, say ‘demo1’ can be created. From the startup menu,

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


click settings and then the item ‘Control panel’. The control panel will look as shown in
the figure 1. Now click the item ODBC(32bit). Then ODBC Data Source
Administrator dialog box will appear as shown in the figure 2. In this box you will find
the list of Data Source names registered with ODBC. The name ‘demo1’ is not there.
.Click the item Add. You will get the Create new Data Source Dialog Box as shown in
the figure 3. In this Box select the driver ‘Microsoft Access Driver(*.mdb). Then click
Finish. You will get the ODBC Microsoft Access 97 setup dialog box as shown in the
figure 4. Click OK. Click OK. You will get the updated ODBC Data Source Dialog
Box as shown in the figure 5 and you will find the newly added item ‘demo1’..

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 3

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 5

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Project using the Data Source demo2:

Now let us display a database table by name employee in the database ‘infotech’.
Create a Standard EXE project. Place a Addoc control and a DataGrid Control in the
form as shown in the figure 6.
Set the name property of the Addodc as demo1.
Set the Data Source property of the DataGrid as demo1.
Right-click the Addoc1 and select properties. You will get the Properties Pages window
as shown in the figure 7.
Select Build from the general tab.
You will get the DataLink Properties windowas shown in the figure 7
Select the Driver ‘Microsoft jet 3.51OLE DB Provider’ under general tab. Click next.
Under the Connection tab enter the file name with its full path as shown in the figure 8.
Click the item Test Connection. You must get the message box as shown in the same
figure 8. Click OK. You will get the Property Page window as shown in the figure 9.
Select RecordSource Tab and enter the SQL command as ‘Select * from employee’.
Click OK. You will get back to the design window.
Save and run the project. You will get the output as shown in the figure 10. Now we
have created a data source and connected it to a database table.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 6

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 7

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 8

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 9

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 10

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Establishing Connectiion Programmatically:

Create a Standard EXE project with two forms as shown in the figures 11 and 12
respectively. In the code window of the command button of the form1, enter the code as
shown in the figure 12a. Save and run the two forms separately. The first form is used
to insert values in the table and the second form is used to display the values in the table.
The output window along with the code is shown in the figure 13.

Dim ADOCN As ADODB.Connection


Dim CMD As ADODB.Command

Private Sub Command1_Click()


costring = "DSN=DEMO;UID=ADMIN;PWD=;"
Set ADOCN = New ADODB.Connection
ADOCN.ConnectionString = costring
ADOCN.Open costring
ADOCN.BeginTrans
ADOCN.Execute Text1
ADOCN.CommitTrans
End Sub

Figure 12a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 11

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 12

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 13

x---------------------------------------x
Visual Basic-6

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


17. Crystal Reports

Crystal Report is a Report Writer that comes with the professional edition of Visual
Basic. It is used to perform the following functions.

1. Design how the report looks


2. Add groupings that break every time the data in this group is changed.
3. Add subtotals based on these groupings, if desired.

The Report Writer is designed in two steps.

1. Design the report layout in the crystal reports design environment.


2. Write code in your Visual Basic application that runs the report designed in the
previous step.

To access the design environment - simply click the Add – Ins | Report Designer
menu option. This brings up two registration screen which contains information for
registering your product as shown in the figures 1 and 2. When registration is complete
you get the crystal reports screen as in the figure 3

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 3

The Crystal Report Screen presents you with 8 options for creating Reports. We will
select the Standard Expert and follow the steps prescribed by it. On selecting the
Standard Expert, you are presented with the screen as shown in the figure 4. Here you
select the datafile and then select next. Youi are now presented with a screen as shown in
the figure 5, where you select the database file ‘payroll’ by browsing. After selecting the
file name click next. You will be presented with a screen as shown in the figure 6,
where you select the fields to be given in the Report. On clicking next, you will get the
screen as shown in the figure 7, where you select the name of the group field and the sort
order of the fields within the group. The next screen is figure 8 where you select the
field which is to be summed. On clicking the Preview Sample, you will get the screen as
shown in the figure 9, which gives the template for the final report. On clicking the
Preview Report, you will get the final Report Screen as shown in the figure 10. Save the
report as sal.rpt and close Crystal Report.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 5

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 6

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 7

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 8

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 9

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 10

Using the ActiveX Crystal Report Control:

Open the Standard EXE window. Drag the Crystal Report Control and a command
button on the form, size them and position them as shown in the figure 11. Open the
property window of the Crystal Report and set the report file name by browsing and the
selection formula as empty. Open the code window for the command button and enter
the code as shown in the figure 11a

Private Sub Command1_Click()


CrystalReport1.Action = 1
End Sub

Figure 11a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Save and run the project. You will get the final report as shown in the figure 12.

Figure 11

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 12

There are different types of Reports that you can generate with Crystal Reports and a
brief summary is given below. One can experiment with them comfortable as they are
all guided by series of menu screens.

The Listing Report:

The listing report presents you with a series of four successive steps that guide you
through the process of creating report. These steps are exactly the same as standard report
the only difference is type of the report produced will just look like a list of information.

The Cross – tab Expert

The cross tab expert presents you with a series of four successive steps. All except the
third step, are the same as the standard expert. A cross tab is a spread sheet-style report
that enables you to compare columns versus rows of data that you specify. This is a
valuable report because you do not have to know how many data items are to appear on

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


the x-axis before the report is run. One final thing to do is to select the summary field that
will appear in the center data section on the report.

The Mail label expert

The mail label expert presents you with a series of five successive steps in the process
of creating labels. All steps, except the fourth step, are the same as the steps in the
standard expert. The fourth step the label tab is used to select any one of the label styles
given or you can define your own.

The Summary expert

The summary expert presents you with a series of eight successive steps that guide
you through the process of creating a summary report. All steps, except for the sixth step,
are the same as the standard expert. The sixth step, the summary & Drilldown tab is used
to define how to summarize and drill down on detail, based on groupings you’ve selected
in the previous steps. Therefore you can choose whether or not to show these sections.

The Graph expert

The graph expert presents you with a series of nine successive steps. Step 6 for the top
n tab; is used to define how the report will select totals. You can select the top n number
of records, where you specify the value for n. step 7, the graph tab, enables you to select
the type of the graph to place on the report and to set attributes.

The Top N expert

The Top N expert presents you with a series of eight successive steps that guide you
through the process of creating hierarchical, detail-oriented report.

The Drill Down expert

The Drill down expert presents you with a series of eight successive steps. It is
essentially the same as Top N expert, except that you can choose which grouping sections
to show or hide.

Creating reports manually

To create a report manually, you can either create it completely from scratch or use
one of the experts mentioned above. When you are in design time view, you can begin
manipulating the objects on the report.

Adding group sections

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The next step is to add group sections of your report. To add a group section, select
the Insert | Group section menu option. This option invokes the select field dialog box
that prompts you to select a field on which the group section is to be based.

Adding fields to a new report

You can add different types of fields to a report.

• Database fields
• Text fields
• Formula fields
• Special fields
• Subtotal/grand total fields
• Graphic fields
• Object fields

A database field is a field that prints data that is retrieved directly from a database.

A text field is used simply as a label. It can identify a field, region of the report, title
or anything else. It is necessary for these purpose you would not use a Database field and,
most likely, not a formula field.
A formula field inserts the results of a formula into a report. A formula can be
virtually anything. For example, a formula can be a constant value, such as
“WELCOME”, which is effectively the same as text field. It can be a static formula such
as 5 * 10; it can be a date or time or even a Database field name.

A special field cannot be defined by the user. These fields are predefined in crystal
reports. Here’s a list of them

• Print date field


• Page number field
• Record number field
• Group number field

A subtotal field or a grand total field very often is used to insert a subtotal or a grand
total at a logical break in your report. The nice thing about these fields is that crystal
reports keeps track of running totals internally.

Graphic fields

To insert a graphic field, select one of the appropriate icons on the toolbar or specify
any one of the following options.

• Insert | Line menu option


• Insert | box menu option

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


• Insert | picture menu option
• Insert | graph / chart expert menu option

Object fields

To insert an object field, select Insert | object menu option. You are prompted for the
type of OLE object you would like to insert.

File location and aliases

When you add a Database file to the report, you select the location of the file, which is
stored internally with the report. But what happens if you move the location of the
database? There is a menu option called Database | set location that enables you to
reassign where the database is located. A dialog box appears so you can select the
appropriate location.

More Details about Crystal Reports:

Crystal Reports lets you customize many of the program’s default settings to fit the ay
you work. These settings affect such things as:
your working environment,
the way you select databases,
SQL and ODBC access,
the way various data types are formatted, and
the fonts you use for fields and text.

To change your default settings, choose the Options command from the File menu.
The File Options dialog box appears. Click the tab appropriate to the option you want
to change, as in the examples below. With the options feature these changes are easy
to make.

Configuration examples
When configuring Crystal Reports you may want to specify the default data directory
that is used when creating new reports, and what kinds of databases will be listed in
the Choose Database File dialog box whenever it appears. For complete descriptions
of all configuration options, search for File Options command in Crystal Reports
Help.

To specify a default data directory


1 Click the Database Tab in the File Options dialog box. Database options appear.
2 Specify your default directory using one of the following methods:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Type the full path in the Data Directory box (C:\CRW for example), or
Click the Browse button, make your selection using the Set Directory dialog box
when it appears.

3 Click OK when finished to return to the Database Tab.

To specify the types of databases listed in the Choose Database File dialog box
When you specify the types of databases to be listed in the Choose Database File
dialog box, you limit the types of files listed. You may choose to do this when you
are only working with one or two types of databases and you want only those types to
be available in the File Name scroll box.
1 Click the Database Tab in the File Options dialog box. Database options appear.
2 In the Database Selector edit box, type the filename extensions for the types of
databases you want listed in the Choose Database File dialog box.
3 Click OK when finished to return to the Database Tab.

Note When entering filename types (*.db; *.ddf; *.ovd, etc.) in the Database
Selector box you must: place an asterisk before the extension, and a semicolon
between file types.

To specify the default view used to preview your report


The default view is the view that Crystal Reports will use when you view your report
in the Preview Window. After the report has been displayed in the default view, you
can select a different view if necessary.
1 Click the Layout Tab in the File Options dialog box. Layout options appear.
2 In the lower left corner of the tab are the Preview Pages options: Fit Size, Fit
Width, and Fit Page. Select one of the three choices to specify the default view you
want Crystal Reports to use when you view pages in the Preview Window.
3 Click OK to return to the program.

Now each time you view a report in the Preview Window, Crystal Reports will start
with the option you selected.

To specify the default fonts for a section of your report


1 Click the Font Tab in the File Options dialog box. Font options appear.
2 The Font Tab has two vertical rows of buttons; one row for changing Default Field
Fonts, and the other row for changing Default Text Fonts. Click the button
corresponding to the section you wish to change the default font for. The Font
dialog box appears.
3 Select the desired font, style and point size to be used as the default, and click OK
when finished to return to the Font Tab.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


For each section that you want to change the default font for, repeat steps 2 and
3 above.

4. Click OK again to return to the program.

Now each time you use a Field Font or a Text Font that you changed the section
default for, the font you selected will be used in that section. All the fields and text
you place in each section of your report will appear using the default fonts you
specified for that section.

To specify a SQL/ODBC server as your primary data source


Specifying a SQL/ODBC server as your primary data source is a four step process:
set the Prefer to Create new reports from SQL Tables option,
select the Server Type
select the Skip Server Type Dialog, and
enter the Server Name, Database, and User ID.

This requires you to work with two of the tabs in the File Options dialog box: New
Report, and SQL.

To set the Prefer to Create new reports from option


1 Click the New Report Tab in the File Options dialog box. New Report Options
appear.
2 Select the SQL Tables option from the Prefer to create new reports from section.

To select the Server Type


1 Click the SQL Tab in the File Options dialog box. SQL options appear.
2 Select the appropriate Server Type from the Server Type drop down box. The data
source appears in the edit box.

To skip the Server Type dialog


1 While still in the SQL Tab, toggle the Skip Server Type dialog check box On.

To enter the Server Name, Database, and User ID


1 Enter the desired server name into the Server Name edit box.
2 Enter the desired database name into the Database edit box.
3 Enter the desired User ID into the User ID edit box.
4 Click OK to return to the program.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Note If you turn off the Use Report Gallery for new reports option after specifying
a SQL/ODBC Server as your primary data source, when you begin a new report
you will bypass the Report Gallery and go straight to the SQL dialog box.

To Turn off the Use Report Gallery for new report option
1 Click the New Report Tab in the File Options dialog box. New Report options
appear.
2 Toggle the Use Report Gallery for new reports option Off.
3 Click OK to return to the program.

Note If the check mark is not visible in the checkbox, Use Report Gallery for new
reports is already off.

Now when you choose the New Report command from the File menu or click the
New Report button on the button bar, you go straight to the dialog box specific to
logging on to the server you selected. Simply enter the correct User ID and Password
to log onto the server.

To specify a report template as your primary data source


1 Click the New Report Tab in the File Options dialog box. New Report options
appear.
2 Toggle the Prefer to create new reports from Other Reports option On.
3 Click OK to return to the program.

Now when you choose the New Report command from the File menu or click the
New Report button on the button bar, the Select Report Template dialog box appears,
listing report templates. Select the report you want to use as a template, and click OK
to open the template.

To specify the default settings Crystal Reports uses for formatting fields
These default settings will be used for formatting fields when you begin a new report.
You can specify the default settings that you will use for most of your reports.
1 Click the Fields Tab in the File Options dialog box. Field formatting options
appear.
2 Select the field type you want to change formatting options for. A dialog box
appears with formatting options for the field type.
3 Make the changes you want to the default settings in the dialog box, and click OK
to return to the Fields Tab.
For each field type you want to change default options for, repeat steps 2 and 3
above.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


4 Click OK to return to the program.

Now whenever you have any of the fields in your report that you have set formatting
options for, they will automatically be printed using that formatting as specified

Use the following steps as a guide for building reports with Crystal Reports.
Note You must create the reports you intend to have available through your
application before you begin working with the Custom Controls. You cannot create
reports using the Custom Controls.

Getting Started
1 Open Crystal Reports.

1 Click the New Report button on the button bar. The Report Gallery appears.
click one of the Report Creation Expert buttons for step-by-step help in creating
a report,
click the Another Report button to use another report as a template for building
your report, or
click the Custom button to build a custom report.

3 When you click the Custom button, the Report Gallery expands.

Note The Report Gallery will not appear if you choose the New command on the
File menu to create a new report. The Report Gallery will only appear when you
click the New Report button on the button bar and you have the Use Report
Gallery for new reports check box toggled On in the New Report Tab of the File
Options dialog box.

Selecting a Report Type


1 Click the Report Type button for the report you want to create:
Click the Custom Report button to create a standard report in a row/column or
data block format.
Click the Custom Cross-Tab button to create a Cross-Tab report that presents
summarized data in a row versus column structure similar to that of a
spreadsheet. Cross-Tab reports are easy to read and are useful for making rapid
comparisons or identifying trends.
Click the Custom Mail Label button to create mailing labels or label-type items.

Selecting a data source

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


1 Click the Data Type button to choose the data source you want to use to create your
report:
Click the Data File button to activate one or more database tables for use in your
report. The Choose Database File dialog box appears. Select a database table to
activate for your report and click OK when finished.
Click the SQL Table button to open any of the wide variety of SQL data sources
that Crystal Reports supports. The Log On Server dialog box appears. Log on to
the desired server and then choose the desired SQL tables for use in your report.

Linking Database Tables


If you have selected two or more database tables, you will need to link them. You link
database tables so records from one database will match related records from another.
To link, use a field that is common to both databases. Crystal Report uses the link to
match up records from one database with those from the other.
When you choose multiple tables, the Visual Linking Expert will appear. Use the
Visual Linking Expert to link two or more databases together. You can link database
tables manually or automatically.

Manually
1 Highlight a field in the database you want to link from that is common to a field in
a second database that you want to link to.
2 Drag the field from the first database to the second. If the link is possible, a link
line will appear to indicate a successful link.
3 To edit a link, highlight the link line and click the Options button. The Link
Options dialog box appears where you can make the desired changes.

Automatically
1 Click the Smart Linking button in the Visual Linking Expert.
2 The Smart Linking feature will create logical links between tables in your report
automatically. If links are not possible, a message will be issued.

Understanding the Design environment


The Design Window appears with an empty Title, Page Header, Details, Page Footer
and Summary section for use in designing your report. You create your report by
inserting and formatting items in each of these sections.
Each report section has its own printing characteristics:
the Title section prints once, at the beginning of the report,

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


the Page Header section prints at the beginning of each page,
the Details section prints once for each record,
the Page Footer section prints at the end of each page, and
the Summary section prints once, at the end of the report.

It is important to understand these characteristics because they affect when and how
often things get printed.

Selecting fields
The Insert Database Field dialog box appears on screen with the Design Window
when you open a new report. This dialog box displays a list of fields and tables in the
current database available for use in your report. To speed the entry of multiple fields,
the box remains on screen until you click the Done button.
1 Select the field(s) you want to appear on the report. You can:
highlight one field at a time, click the Insert button, and then place the field on
your report,
highlight one field at a time and drag it onto your report,
use the Shift-Click combination to select a number of contiguous fields or the
Ctrl-Click combination to select fields from the list at random and drag them
onto your report.

Note If you placed multiple fields, they will appear next to each other in the order
they appear in the Insert Database Field dialog box.

Crystal Reports marks the position of each field with a rectangular box. The
characters in the box indicate whether the field is text (XXX...), number (555...),
currency ($555...), date (12/31/99), or Boolean (T/F). The number of characters in
the box indicates the number of characters allowed for the field in the database.
You can change the appearance of fields by choosing the Options command from
the File menu and clicking the Show Field Names Option On on the Layout Tab of
the File Options dialog box. Each field will now be indicated by its name rather
than the corresponding character.

Crystal Reports will automatically place corresponding field titles for each field in
the Page Header section directly above the corresponding field. You can disable
this option by choosing the Options command from the File menu and clicking the
Insert Field Titles option Off on the Layout Tab of the File Options dialog box.

Moving, resizing, formatting and deleting fields


1 To move, resize, format, add borders and colors, delete, or insert a subtotal,
summary or grand total for a field, you first have to click the field to select it.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


When you select a field, black handles appear on the right and left sides to indicate
it is selected.
Note You can select multiple fields at one time using the Shift-Click method, or by
choosing the Select Fields command from the Edit menu. The Select Fields
command activates a cross-hair cursor you can use to drag and draw a rectangle to
surround the desired field(s), known as the marquee selection technique.

2 Once a field is selected, you then tell Crystal Reports what you want to do with it:
To move a field, drag the field to the desired position.
To resize a field, drag the right or left handle until the field is the desired size.
To format a field (alignment, number, currency, date display, etc.), right-click
the field and choose the Change Format command from the shortcut menu. A
Format dialog box appears specific to the data type of the selected field. Make
the desired changes and click OK when finished.
To set up borders, background fill and drop shadows, right-click the field and
choose the Change Border and Colors command from the shortcut menu. The
Format Border and Colors dialog box appears. Make the desired selections and
click OK when finished.
To change the font, right-click the field and choose the Change Font command
from the shortcut menu. The Font dialog box appears. Make the desired changes
and click OK when finished.
To delete a selected field, simply press Delete.

Note When you right-click a field, it selects the field and displays a shortcut menu
in one single step.

Note Many of the font and formatting options are also available as buttons on the
format bar.

Sorting report data


You may want to change the way data is sorted within your report. Sorting means the
order in which values are displayed. Information in a phone book, for example, is
sorted alphabetically by name to create an order and speed efficiency in accessing the
data contained within it.
When you sort in Crystal Reports, the program asks you to select two things: the field
you want your sort to be based on (sort field), and the sort direction (Ascending
meaning smallest to largest, 1 to 9, A to Z, False to True or Descending meaning
largest to smallest, 9 to 1, Z to A, True to False).
A sort field is a field that determines the order in which data appears in your report.
You can use any field as a sort field. When you select a sort field, Crystal Reports
sorts the records in the report based on the values in the selected field. Your Regional

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


or International settings and the field’s data type determine the method in which the
data for the field is sorted. For example, if your settings are for the United States:
String fields

Single character values are sorted so that blanks have the lowest value, then
punctuation, then numbers, then uppercase letters, and finally lowercase letters.
Then two character values are sorted, then three, etc., using the same rules.
Currency fields

Currency fields are sorted in numeric order.


Number fields

Number fields are sorted in numeric order.


Date fields

Date fields are sorted in chronological order.


Boolean Fields

Boolean Fields are sorted so that false values (0) come first, then true values (1).

Crystal Reports allows you to perform single field or multiple field sorts. Single field
sorts are sorts in which all the records used in the report are sorted based on the
values in a single field. In multiple field sorts, Crystal Reports first sorts the records
based on the values in the first field selected, putting them in ascending or descending
order as specified. When two or more records have the same field value in the first
sort field, it then sorts those records (and those alone) based on the value in the
second sort field. For example, in a sort based on last name and then first name (in
ascending order), “Smith, Bob” would be returned before “Smith, John.”
1 Click the Sort Records button on the button bar. The Record Sort Order dialog box
appears.
2 Highlight the field(s) to be sorted from the Report Fields list box.
3 Click the Add button. The highlighted field(s) will be added to the Sort fields list
box.
4 Specify the sort direction by clicking the corresponding option button. Choose
from either Ascending (A to Z, 1 to 9) or Descending (Z to A, 9 to 1).
5 Click OK when finished to return to your report. Crystal Reports will sort the
records as specified.

Grouping report data


Crystal Reports enables you to group data in your report. A group is a set of records
that are related to each other in some way. For example, in a customer list, a group

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


could consist of all those customers living in the same zip code, or in the same state.
In a sales report, a group could consist of all the orders placed by the same customer,
or all of the orders generated by a specific sales representative.
Crystal Reports allows you great flexibility in grouping data. It also gives you the
ability to create a number of different kinds of group values.
A group value is the value generated as the result of an evaluation, a tally, or a
calculation performed on data from a single group. A subtotal is one kind of group
value; it is the sum of all of the values from a single field, from all the records in a
group. In a sales report, for example, if you subtotal sales by sales representative,
Crystal Reports gathers all the records that belong to the sales representative and
totals the sales amounts from all the records. In a group average, Crystal Reports
averages the values in a group of records; in a group count, it counts the values in a
group of records, etc. Group values are important tools for creating powerful reports.
Crystal Reports gives you several alternatives for working with group data. It enables
you to:
calculate the sum of values,
calculate the standard deviation or variance of the values,
average the values,
count the values,
determine the highest value, and
determine the lowest value in the group.

While there may be many data fields on a report, there is typically only one field for
which you are interested in grouping the data. In a sales report, for example, it would
probably be the field listing the amount of sales; in a commission report, it would
probably be the field listing the amount of commission, etc.
1 When you group data in your report, first select the field you want to group.
2 Once the field is selected, choose the Group Section command from the Insert
menu. The Insert Group Section dialog box appears.
3 Select a field (a sort and group by field) to trigger grouping whenever its value
changes. In grouping your data by state, for example, you would use the state field
to create a new group (and generate a group value if selected) whenever the state
changes. Likewise, the ZIP code field would trigger a grouping whenever the ZIP
code changes.

Once you have made these simple selections, Crystal Reports groups the data as
specified.

Creating Custom Groups


Most of the time you sort and group your data based on the values in a field in your
report. For example, if you have a customer list and you want to sort and group it by

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


state, the program first sorts the list by state and then breaks the list into state groups
whenever the value in the State field changes.
Sometimes, however, you may not want to group based on the values found in one of
the fields on your report.
Your report may not contain the field you want to group on. For example, your
report contains a City field and a State field but no Country field, but you want to
group by county.
Your report may contain the field you want to group on, but you are not happy with
the grouping based on the values in that field. For example, you have a Color field
on your report that includes specific color names (Logan Green, Sky Blue, Emerald
Green, Navy Blue, etc.) but you want all "flavors" of each color to appear as a
single group (Greens, Blues, Reds, etc.).
Your report may contain the field you want to group on, but you want to select
specific values or ranges of values for each group. For example, you might want
one group to contain records where gross sales are less than a certain value, a
second group where gross sales are greater than a certain value, and a final group
where gross sales fall between two values.

Crystal Reports provides specified order grouping as a solution to these custom


sorting and grouping challenges. Specified order grouping enables you to create the
groups you want to appear on your report and the records that each group contains.
Your only real limitation is that a record can be assigned to only one group.
To use Specified Order grouping, select in specified order as your sort option
whenever the program provides you with that option. The program gives you the in
specified order option whenever you create groups using the Group, Subtotal, or
Summary command on the Insert menu or whenever you create groups while building
a report using one of the Report Creation Experts.

Summarizing and totaling


When Crystal Reports summarizes and totals data, it breaks it into groups and then
performs the specified operation on the values in each group. It does this
automatically; all you have to do is specify:
the field you want summarized/totaled,
the type of operation to be performed on the field,
the field that is going to trigger a new group whenever its value changes, and
the sort order.

Inserting a Subtotal
1 To insert a subtotal (for numeric fields only), right-click the field and choose the
Insert Subtotal command from the shortcut menu. The Insert Subtotal dialog box
appears.
2 Select the field you want to trigger a new subtotal whenever its value changes.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


3 Specify the sort direction: Ascending (A to Z, 1 to 9) or Descending (Z to A, 9 to
1).
4 Crystal Reports creates a Group Header and Group Footer section and
automatically places the subtotal in the Group Footer section.

Inserting a Grand Total


1 To insert a grand total (or a report average, a report count, etc.) at the end of the
report, right-click the field and choose the Insert Grand Total command from the
shortcut menu. The Insert Grand Total dialog box appears.
2 Select the desired operation from the drop down list and click OK when finished.
3 Crystal Reports creates a Grand Total section to hold the grand total.

Inserting a Summary
1 To insert a summary (count, sum, average, standard deviation, variance, minimum,
maximum, etc.), right-click the field and choose the Insert Summary command
from the shortcut menu. The Insert Summary dialog box appears.
2 Select the field you want to trigger a new summary whenever its value changes.
3 Specify the sort direction: Ascending (A to Z, 1 to 9) or Descending (Z to A, 9 to
1).
4 Crystal Reports creates a Group Header and Group Footer section and
automatically places the summary in the Group Footer section.

Selecting records
When you select a field to appear in your report, Crystal Reports, by default, prints
field values from every record in the active database table(s). In many cases, you may
not want to include all the values, but only a subset of those values. For example, you
may want to include records only for a specific group of customers or for a specific
range of account numbers out of the total number of records in the active database
table. With Crystal Reports, this is easy.
When you select records, you are telling Crystal Reports to base your report only on
those records that meet some conditions that you set. You base those conditions on
what kind of information you want in your finished report.
Assume, for example that you want a report that only shows California data. Your
challenge is to find the best way to identify those records that come from California.
If the table that you are using for your report has a state field or a region field, you
can specify in your request that the program use only those records where the value
in that field is equal to California.
If the table does not have a state field and you still want to report only on
California data, you may be able to identify the data in some other way. For
example, if the table has a postal code or area code, you could base your record

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


selection on the range of postal codes that apply to California (Postal Code is
between n and N), or on California area codes (Area Code is one of x, y,....z).

Crystal Reports Select Records Expert makes it easy to specify the records you want
included in your report. You simply select the field that you want to base your
selection on and then set the selection criteria. If you want to set additional criteria for
the selected field or if you want to base record selection on additional fields, the
Expert provides the tools you need to do it.
You can begin your work in the Select Records Expert in one of two ways:

Highlight the field in your report on which you want to base record selection and
click the Select Records button on the button bar. The program opens the Select
Records Expert, ready for you to set the conditions on the highlighted field.
Without highlighting a report field, click the Select Records button. The Choose
Field dialog box appears. Select the field you want to base your selection on and
click OK. The Select Records Expert appears.

To select records
1 Open the Select Records Expert.
2 Use the drop down boxes to enter your selection criteria for the selected field.
3 If you want to base your record selection on more than one field, click the New
Tab and choose your next field from the Choose Field dialog box when it appears.
4 Click OK when finished to return to your report. Crystal Reports will perform the
record selection as specified.

Top N
Many times, you might want to show only the top or bottom groups in a report: the
fastest selling product lines, the least productive sales regions, the states that generate
the most orders. Because this kind of group selection is so popular, the program
includes a facility for setting it up easily.
You set up Top N (or Bottom N) group selection using the Top N/Sort Group Expert
command on the Report menu. Using this expert, you specify whether you want to
display the Top N or Bottom N groups, and then you specify what number N is.
For example:
if you want to report on the three fastest selling product lines, select top N and set
N to be equal to three, or

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


if you want to report on the five least productive sales regions, select bottom N and
set N to be equal to five.

The program will display those groups to your specifications.


But there is one other consideration with Top N group selection and that is what to do
with all the records from other groups that do not fit the Top N or Bottom N criteria
you set. You need to decide whether to eliminate those records from your report
entirely or to lump them altogether in a single group with the name you specify. The
program enables you to do either by toggling the include Others, with the name check
box On or Off accordingly in the Top N/Sort Group Expert.

Creating formulas
If you want to create a formula to calculate numeric values, compare one value to
another and select alternative actions based on the comparison, join multiple text
strings into a single string, make data calculations or comparisons, etc.:

1 Click the Insert Formula button on the button bar. The Insert Formula dialog box
appears.
2 Enter a name for your formula and click OK. The Formula Editor appears. Use the
Formula Editor to create, test and modify your formula.
3 Enter fields, operators, and functions into the Formula text box by double-clicking
them in their respective list boxes. You can get complete information on each
available Function and Operator via the Help button.

Note Each formula is a text string that can be typed directly in to the Formula text
box as well as selecting components from the list boxes.

4 When finished editing, click the Accept button. Crystal Reports checks the formula
syntax, and if correct, closes the Formula Editor.
5 Place the formula field where you want it to appear in your report.

Adding a graph/chart
Crystal Reports enables you to include sophisticated, colorful charts and graphs in
your reports.
When you add a graph to your report, you are graphing summary and subtotal
information. Before you can add a graph, therefore, you must have at least one group
and one summary or subtotal in your report. For example, if you have a sales report
grouped by State and a subtotal of Last Year’s Sales for each State, you can quickly
create a graph that will display sales by state.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Adding and modifying your graphs is easy in Crystal Reports with the use of the
Graph/Chart Expert. Use the Expert every time you create or modify graphs. The
Expert walks you through the creation of your graphs step-by-step.

1 Click the Insert Chart button on the button bar to access the Graph/Chart Expert.
Types Tab
When you begin creating your graphs, you will need to choose one of the many
graph types available. To select a graph type, click the button that corresponds to
the graph type you want.
Data Tab
In the Data Tab, select what data you want to graph on, how often you want it to
print (dependent on where you want it displayed), and what you want to show in
the graph.
The graph on drop-down box displays all the summaries and subtotals on your
report. Simply select which one you want to base your graph on.
Text Tab
The Text Tab allows you to enter labels for your graph by inserting titles,
footnotes, and axis titles when appropriate. Simply type the text into the
corresponding boxes. The program will only use the labels appropriate for the
graph type that you chose earlier. The others will be ignored.
Options Tab
The Options Tab enables you to place a legend on your graph, a maximum or
minimum limit on the graph values, or a number of other options.

OLE Objects
Crystal Reports is an OLE container application. Thus it allows you to place OLE
objects in your report. To do this:
1 Choose the Object command from the Insert menu.
2 Insert an existing object by choosing the Create from file option and selecting the
desired object, or create a new object by choosing the Create New option then an
object type. The corresponding application will open where you can create the
object as desired.
3 If you want to edit the object, simply double-click it and the program in which it
was created (or a similar application that allows such editing) will open.
4 Modify the object as desired, save it and Crystal Reports automatically updates the
object in your report.

Adding a report title

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


1 To add a title to your report, click the Insert Text Field button on the button bar.
The Edit Text Field dialog box appears.
2 Type the desired title into the Enter Text edit box and click Accept when finished.
3 Place the text field where you want it to appear in the Title section of your report.

Previewing your report

1 To preview your report at any time, click the Print Preview button on the button
bar. The Preview Tab appears displaying the results of your report.
2 You can fine tune your report in the Preview Tab if you wish or close the window
and continue working on your report in the Report Designer. The functionality is
the same in both places.

Saving your report

1 Save your report often by clicking the Save button on the button bar.
Printing your report
1 If you want to print a hard copy of your report, click the Printer button on the
button bar. The Print dialog box appears.
2 Select the pages you want to print, the number of copies you want, etc., as desired.
3 Click OK. Crystal Reports prints your report.
x-----------------------------------------------------------------x

Visual Basic-6
18. Visual Basic Syntax

Syntax is concerned with learning the grammar rules for coding the different
entities like variables, constants, operators, expressions, statements etc.

Variables:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


You often need to store values temporarily when performing calculations with
Visual Basic. For example, you might want to calculate several values, compare
them, and perform different operations on them, depending on the result of the
comparison. You need to retain the values if you want to compare them, but you
don't need to store them in a property.
Visual Basic, like most programming languages, uses variables for storing values.
Variables have a name (the word you use to refer to the value the variable
contains) and a data type (which determines the kind of data the variable can
store). Arrays can be used to store indexed collections of related variables.
Constants also store values, but as the name implies, those values remain
constant throughout the execution of an application. Using constants can make
your code more readable by providing meaningful names instead of numbers.
There are a number of built-in constants in Visual Basic, but you can also create
your own.
Data types control the internal storage of data in Visual Basic. By default, Visual
Basic uses the Variant data type. There are a number of other available data
types that allow you to optimize your code for speed and size when you don't
need the flexibility that Variant provides.
In Visual Basic, you use variables to temporarily store values during the execution of
an application. Variables have a name (the word you use to refer to the value the
variable contains) and a data type (which determines the kind of data the variable
can store).
You can think of a variable as a placeholder in memory for an unknown value.
For example, imagine you are creating a program for a fruit stand to track the
sales of apples. You don't know the price of an apple or the quantity sold until
the sale actually occurs. You can use two variables to hold the unknown values
— let's name them ApplePrice and ApplesSold. Each time the program is run,
the user supplies the values for the two variables. To calculate the total sales and
display it in a Textbox named txtSales, your code would look like this:
txtSales.txt = ApplePrice * ApplesSold

The expression returns a different total each time, depending on what values the
user provides. The variables allow you to make a calculation without having to
know in advance what the actual inputs are.
In this example, the data type of ApplePrice is Currency; the data type of
ApplesSold is an integer. Variables can represent many other values as well: text
values, dates, various numeric types, even objects.

Storing and Retrieving Data in Variables


You use assignment statements to perform calculations and assign the result to a
variable:
ApplesSold = 10 ' The value 10 is passed to the
' variable.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


ApplesSold = ApplesSold + 1 ' The variable is
' ncremented.

Note that the equal sign in this example is an assignment operator, not an
equality operator; the value (10) is being assigned to the variable (ApplesSold).

Declaring Variables
To declare a variable is to tell the program about it in advance. You declare a
variable with the Dim statement, supplying a name for the variable:
Dim variablename [As type]

Variables declared with the Dim statement within a procedure exist only as long
as the procedure is executing. When the procedure finishes, the value of the
variable disappears. In addition, the value of a variable in a procedure is local to
that procedure — that is, you can't access a variable in one procedure from
another procedure. These characteristics allow you to use the same variable
names in different procedures without worrying about conflicts or accidental
changes.
A variable name:
Must begin with a letter.
Can't contain an embedded period or embedded type-declaration character.
Must not exceed 255 characters.
Must be unique within the same scope, which is the range from which the
variable can be referenced — a procedure, a form, and so on.

The optional As type clause in the Dim statement allows you to define the data
type or object type of the variable you are declaring. Data types define the type
of information the variable stores. Some examples of data types include String,
Integer, and Currency. Variables can also contain objects from Visual Basic or
other applications. Examples of Visual Basic object types, or classes, include
Object, Form1, and TextBox.
There are other ways to declare variables:
Declaring a variable in the Declarations section of a form, standard, or class
module, rather than within a procedure, makes the variable available to all
the procedures in the module.
Declaring a variable using the Public keyword makes it available throughout
your application.
Declaring a local variable using the Static keyword preserves its value even
when a procedure ends.

Implicit Declaration

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


You don't have to declare a variable before using it. For example, you could
write a function where you don't need to declare TempVal before using it:
Function SafeSqr(num)
TempVal = Abs(num)
SafeSqr = Sqr(TempVal)
End Function

Visual Basic automatically creates a variable with that name, which you can use
as if you had explicitly declared it. While this is convenient, it can lead to subtle
errors in your code if you misspell a variable name. For example, suppose that
this was the function you wrote:
Function SafeSqr(num)
TempVal = Abs(num)
SafeSqr = Sqr(TemVal)
End Function

At first glance, this looks the same. But because the TempVal variable was
misspelled on the next-to-last line, this function will always return zero. When
Visual Basic encounters a new name, it can't determine whether you actually
meant to implicitly declare a new variable or you just misspelled an existing
variable name, so it creates a new variable with that name.

Explicit Declaration
To avoid the problem of misnaming variables, you can stipulate that Visual
Basic always warn you whenever it encounters a name not declared explicitly as
a variable.

To explicitly declare variables

Place this statement in the Declarations section of a class, form, or standard


module:
Option Explicit
– or –
From the Tools menu, choose Options, click the Editor tab and check the
Require Variable Declaration option. This automatically inserts the Option
Explicit statement in any new modules, but not in modules already created;
therefore, you must manually add Option Explicit to any existing modules
within a project.

Had this statement been in effect for the form or standard module containing the
SafeSqr function, Visual Basic would have recognized TempVal and TemVal as
undeclared variables and generated errors for both of them. You could then
explicitly declare TempVal:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Function SafeSqr(num)
Dim TempVal
TempVal = Abs(num)
SafeSqr = Sqr(TemVal)
End Function

Now you'd understand the problem immediately because Visual Basic would
display an error message for the incorrectly spelled TemVal. Because the Option
Explicit statement helps you catch these kinds of errors, it's a good idea to use it
with all your code.
Note The Option Explicit statement operates on a per-module basis; it must be
placed in the Declarations section of every form, standard, and class module for
which you want Visual Basic to enforce explicit variable declarations. If you
select Require Variable Declaration, Visual Basic inserts Option Explicit in all
subsequent form, standard, and class modules, but does not add it to existing
code. You must manually add Option Explicit to any existing modules within a
projec
Scoping Variables
The scope of a variable defines which parts of your code are aware of its
existence. When you declare a variable within a procedure, only code within that
procedure can access or change the value of that variable; it has a scope that is
local to that procedure. Sometimes, however, you need to use a variable with a
broader scope, such as one whose value is available to all the procedures within
the same module, or even to all the procedures in your entire application. Visual
Basic allows you to specify the scope of a variable when you declare it.
Depending on how it is declared, a variable is scoped as either a procedure-level
(local) or module-level variable.
Scope Private Public

Variables Used Within a Procedure


Procedure-level variables are recognized only in the procedure in which they're
declared. These are also known as local variables. You declare them with the
Dim or Static keywords. For example:
Dim intTemp As Integer
– or –
Static intPermanent As Integer

Values in local variables declared with Static exist the entire time your
application is running while variables declared with Dim exist only as long as the
procedure is executing.
Local variables are a good choice for any kind of temporary calculation. For
example, you can create a dozen different procedures containing a variable

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


called intTemp. As long as each intTemp is declared as a local variable, each
procedure recognizes only its own version of intTemp. Any one procedure can
alter the value in its local intTemp without affecting intTemp variables in other
procedures.

Variables Used Within a Module


By default, a module-level variable is available to all the procedures in that
module, but not to code in other modules. You create module-level variables by
declaring them with the Private keyword in the Declarations section at the top of
the module. For example:
Private intTemp As Integer

At the module level, there is no difference between Private and Dim, but Private
is preferred because it readily contrasts with Public and makes your code easier
to understand.

Variables Used by All Modules


To make a module-level variable available to other modules, use the Public
keyword to declare the variable. The values in public variables are available to
all procedures in your application. Like all module-level variables, public
variables are declared in the Declarations section at the top of the module. For
example:
Public intTemp As Integer

Note You can't declare public variables within a procedure, only within the
Declarations section of a module.
Using Multiple Variables with the Same Name
If public variables in different modules share the same name, it's possible to
differentiate between them in code by referring to both the module and variable
names. For example, if there is a public Integer variable intX declared in both
Form1 and in Module1, you can refer to them as Module1.intX and Form1.intX
to get the correct values.
To see how this works, insert two standard modules in a new project and draw
three command buttons on a form.
One variable, intX, is declared in the first standard module, Module1. The Test
procedure sets its value:
Public intX As Integer ' Declare Module1's intX.
Sub Test()
' Set the value for the intX variable in Module1.
intX = 1
End Sub

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The second variable, which has the same name, intX, is declared in the second
standard module, Module2. Again, a procedure named Test sets its value:
Public intX As Integer ' Declare Module2's intX.
Sub Test()
' Set the value for the intX variable in Module2.
intX = 2
End Sub

The third intX variable is declared in the form module. And again, a procedure
named Test sets its value.
Public intX As Integer ' Declare the form's intX
' variable.
Sub Test()
' Set the value for the intX variable in the form.
intX = 3
End Sub

Each of the three command buttons' Click event procedures calls the
appropriate Test procedure and uses MsgBox to display the values of the three
variables.
Private Sub Command1_Click()
Module1.Test ' Calls Test in Module1.
MsgBox Module1.intX ' Displays Module1's intX.
End Sub

Private Sub Command2_Click()


Module2.Test ' Calls Test in Module2.
MsgBox Module2.intX ' Displays Module2's intX.
End Sub

Private Sub Command3_Click()


Test ' Calls Test in Form1.
MsgBox intX ' Displays Form1's intX.
End Sub

Run the application and click each of the three command buttons. You'll see the
separate references to the three public variables. Notice in the third command
button's Click event procedure, you don't need to specify Form1.Test when
calling the form's Test procedure, or Form1.intX when calling the value of the
form's Integer variable. If there are multiple procedures and variables with the
same name, Visual Basic takes the value of the more local variable, which in this
case, is the Form1 variable.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Public vs. Local Variables
You can also have a variable with the same name at a different scope. For
example, you could have a public variable named Temp and then, within a
procedure, declare a local variable named Temp. References to the name Temp
within the procedure would access the local variable; references to Temp outside
the procedure would access the public variable. The module-level variable can
be accessed from within the procedure by qualifying the variable with the
module name.
Public Temp As Integer
Sub Test()
Dim Temp As Integer
Temp = 2 ' Temp has a value of 2.
MsgBox Form1.Temp ' Form1.Temp has a value of 1.
End Sub

Private Sub Form_Load()


Temp = 1 ' Set Form1.Temp to 1.
End Sub
Private Sub Command1_Click()
Test
End Sub

In general, when variables have the same name but different scope, the more
local variable always shadows (that is, it is accessed in preference to) less local
variables. So if you also had a procedure-level variable named Temp, it would
shadow the public variable Temp within that module.

LifeTime of Variables:
In addition to scope, variables have a lifetime, the period of time during which
they retain their value. The values in module-level and public variables are
preserved for the lifetime of your application. However, local variables declared
with Dim exist only while the procedure in which they are declared is executing.
Usually, when a procedure is finished executing, the values of its local variables
are not preserved and the memory used by the local variables is reclaimed. The
next time the procedure is executed, all its local variables are reinitialized.
However, you can preserve the value of a local variable by making the variable
static. Use the Static keyword to declare one or more variables inside a
procedure, exactly as you would with the Dim statement:
Static Depth

For example, the following function calculates a running total by adding a new
value to the total of previous values stored in the static variable Accumulate:
Function RunningTotal(num)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Static ApplesSold
ApplesSold = ApplesSold + num
RunningTotal = ApplesSold
End Function

If ApplesSold was declared with Dim instead of Static, the previous accumulated
values would not be preserved across calls to the function, and the function
would simply return the same value with which it was called.
You can produce the same result by declaring ApplesSold in the Declarations
section of the module, making it a module-level variable. Once you change the
scope of a variable this way, however, the procedure no longer has exclusive
access to it. Because other procedures can access and change the value of the
variable, the running totals might be unreliable and the code would be more
difficult to maintain.

Declaring All Local Variables as Static


To make all local variables in a procedure static, place the Static keyword at the
beginning of a procedure heading. For example:
Static Function RunningTotal(num)

This makes all the local variables in the procedure static regardless of whether
they are declared with Static, Dim, Private, or declared implicitly. You can place
Static in front of any Sub or Function procedure heading, including event
procedures and those declared as Private.
Often you'll find that your code contains constant values that reappear over and
over. Or you may find that the code depends on certain numbers that are
difficult to remember — numbers that, in and of themselves, have no obvious
meaning.
In these cases, you can greatly improve the readability of your code — and make
it easier to maintain — by using constants. A constant is a meaningful name that
takes the place of a number or string that does not change. Although a constant
somewhat resembles a variable, you can't modify a constant or assign a new
value to it as you can to a variable. There are two sources for constants:
Intrinsic or system-defined constants are provided by applications and
controls. Visual Basic constants are listed in the Visual Basic (VB), Visual
Basic for applications (VBA), and data access (DAO) object libraries in the
Object Browser. Other applications that provide object libraries, such as
Microsoft Excel and Microsoft Project, also provide a list of constants you can
use with their objects, methods, and properties. Constants are also defined in
the object library for each ActiveX control. For details on using the Object
Browser, see "Programming with Objects."
Symbolic or user-defined constants are declared using the Const statement.
User-defined constants are described in the next section, "Creating Your Own
Constants."

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


In Visual Basic, constant names are in a mixed-case format, with a prefix
indicating the object library that defines the constant. Constants from the Visual
Basic and Visual Basic for applications object libraries are prefaced with "vb"
— for instance, vbTileHorizontal. Constants from the data access object library
are prefaced with "db" — for instance, dbRelationUnique.
The prefixes are intended to prevent accidental collisions in cases where
constants have identical names and represent different values. Even with
prefixes, it's still possible that two object libraries may contain identical
constants representing different values. Which constant is referenced in this case
depends on which object library has the higher priority. For information on
changing the priority of object libraries, see the "References Dialog Box" in
Books Online.
To be absolutely sure you avoid constant name collisions, you can qualify
references to constants with the following syntax:
[libname.][modulename.]constname

Libname is usually the class name of the control or library. Modulename is the
name of the module that defines the constant. Constname is the name of the
constant. Each of these elements is defined in the object library, and can be
viewed in the Object Browser.

Creating Your Own Constants


The syntax for declaring a constant is:
[Public|Private] Const constantname[As type] = expression

The argument constantname is a valid symbolic name (the rules are the same as
those for creating variable names), and expression is composed of numeric or
string constants and operators; however, you can't use function calls in
expression.
A Const statement can represent a mathematical or date/time quantity:
Const conPi = 3.14159265358979
Public Const conMaxPlanets As Integer = 9
Const conReleaseDate = #1/1/95#

The Const statement can also be used to define string constants:


Public Const conVersion = "07.10.A"
Const conCodeName = "Enigma"

You can place more than one constant declaration on a single line if you separate
them with commas:
Public Const conPi = 3.14, conMaxPlanets = 9, _
conWorldPop = 6E+09

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The expression on the right side of the equal sign ( = ) is often a number or
literal string, but it can also be an expression that results in a number or string
(although that expression can't contain calls to functions). You can even define
constants in terms of previously defined constants:
Const conPi2 = conPi * 2

Once you define constants, you can place them in your code to make it more
readable. For example:
Static SolarSystem(1 To conMaxPlanets)
If numPeople > conWorldPop Then Exit Sub

Scoping User-Defined Constants


A Const statement has scope like a variable declaration, and the same rules
apply:
To create a constant that exists only within a procedure, declare it within that
procedure.
To create a constant available to all procedures within a module, but not to
any code outside that module, declare it in the Declarations section of the
module.
To create a constant available throughout the application, declare the constant
in the Declarations section of a standard module, and place the Public
keyword before Const. Public constants cannot be declared in a form or class
module.

Numeric Data Types:


Visual Basaic supplies several numeric data types-Integer, Lonbg, Single,
Double and Currency. Using a numeric data type generally uses less storage
space than a variant.
If the variable contains a fraction, declare it as a Single, Double, or Currency
variable. The Currency data type supports up to four digits to the right of the
decimal separator and fifteen digits to the left; it is an accurate fixed-point data
type suitable for monetary calculations. Floating-point (Single and Double)
numbers have much larger ranges than Currency, but can be subject to small
rounding errors.
Note Floating-point values can be expressed as mmmEeee or mmmDeee, in
which mmm is the mantissa and eee is the exponent (a power of 10). The highest
positive value of a Single data type is 3.402823E+38, or 3.4 times 10 to the 38th
power; the highest positive value of
Double data type is a
1.79769313486232D+308, or about 1.8 times 10 to the 308th power. Using D to
separate the mantissa and exponent in a numeric literal causes the value to be

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


treated as a Double data type. Likewise, using E in the same fashion treats the
value as a Single data type.
The Byte Data Type
If the variable contains binary data, declare it as an array of the Byte data type.
Using Byte variables to store binary data preserves it during format conversions.
When String variables are converted between ANSI and Unicode formats, any
binary data in the variable is corrupted. Visual Basic may automatically convert
between ANSI and Unicode when:
Reading from files
Writing to files
Calling DLLs
Calling methods and properties on objects

All operators that work on integers work with the Byte data type except unary
minus. Since Byte is an unsigned type with the range 0 - 255, it cannot represent
a negative number. So for unary minus, Visual Basic coerces the Byte to a signed
integer first.
All numeric variables can be assigned to each other and to variables of the
Variant type. Visual Basic rounds off rather than truncates the fractional part of
a floating-point number before assigning it to an integer.

The String Data Type


If you have a variable that will always contain a string and never a numeric
value, you can declare it to be of type String:
Private S As String

You can then assign strings to this variable and manipulate it using string
functions:
S = "Database"
S = Left(S, 4)

By default, a string variable or argument is a variable-length string; the string


grows or shrinks as you assign new data to it. You can also declare strings that
have a fixed length. You specify a fixed-length string with this syntax:
String * size
For example, to declare a string that is always 50 characters long, use code like
this:
Dim EmpName As String * 50

If you assign a string of fewer than 50 characters, EmpName is padded with


enough trailing spaces to total 50 characters. If you assign a string that is too
long for the fixed-length string, Visual Basic simply truncates the characters.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Because fixed-length strings are padded with trailing spaces, you may find the
Trim and RTrim functions, which remove the spaces, useful when working with
them.
Fixed-length strings in standard modules can be declared as Public or Private.
In forms and class modules, fixed-length strings must be declared Private.

Exchanging Strings and Numbers


You can assign a string to a numeric variable if the string represents a numeric
value. It's also possible to assign a numeric value to a string variable. For
example, place a command button, text box, and list box on a form. Enter the
following code in the command button's Click event. Run the application, and
click the command button.
Private Sub Command1_Click()
Dim intX As Integer
Dim strY As String
strY = "100.23"
intX = strY ' Passes the string to a numeric
' variable.
List1.AddItem Cos(strY) ' Adds cosine of number in
' the string to the listbox.
strY = Cos(strY) ' Passes cosine to the
' string variable.
Text1.Text = strY ' String variable prints in
' the text box.
End Sub

Visual Basic will automatically coerce the variables to the appropriate data type.
You should use caution when exchanging strings and numbers; passing a non-
numeric value in the string will cause a run-time error to occur.

The Boolean Data Type


If you have a variable that will contain simple true/false, yes/no, or on/off
information, you can declare it to be of type Boolean. The default value of
Boolean is False. In the following example, blnRunning is a Boolean variable
which stores a simple yes/no setting.
Dim blnRunning As Boolean
' Check to see if the tape is running.
If Recorder.Direction = 1 Then
blnRunning = True
End if

The Date Data Type


Date and time values can be contained both in the specific Date data type and in
Variant variables. The same general characteristics apply to dates in both types.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


When other numeric data types are converted to Date, values to the left of the
decimal represent date information, while values to the right of the decimal
represent time. Midnight is 0, and midday is 0.5. Negative whole numbers
represent dates before December 30, 1899.

The Object Data Type


Object variables are stored as 32-bit (4-byte) addresses that refer to objects
within an application or within some other application. A variable declared as
Object is one that can subsequently be assigned (using the Set statement) to refer
to any actual object recognized by the application.
Dim objDb As Object
Set objDb = OpenDatabase("c:\Vb5\Biblio.mdb")

When declaring object variables, try to use specific classes (such as TextBox
instead of Control or, in the preceding case, Database instead of Object) rather
than the generic Object. Visual Basic can resolve references to the properties
and methods of objects with specific types before you run an application. This
allows the application to perform faster at run time. Specific classes are listed in
the Object Browser.
When working with other applications' objects, instead of using a Variant or the
generic Object, declare objects as they are listed in the Classes list in the Object
Browser. This ensures that Visual Basic recognizes the specific type of object
you're referencing, allowing the reference to be resolved at run time.

Converting Data Types


Visual Basic provides several conversion functions you can use to convert values
into a specific data type. To convert a value to Currency, for example, you use
the CCur function:
PayPerWeek = CCur(hours * hourlyPay)

Conversion
function Converts an expression to

CBool Boolean
CByte Byte
CCur Currency
CDate Date
CDbl Double
CInt Integer
CLng Long
CSng Single
CStr String
CVar Variant
CVErrError

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Note Values passed to a conversion function must be valid for the destination
data type or an error occurs. For example, if you attempt to convert a Long to
an Integer, the Long must be within the valid range for the Integer data type.
The Variant Data Type
A Variant variable is capable of storing all system-defined types of data. You
don't have to convert between these types of data if you assign them to a Variant
variable; Visual Basic automatically performs any necessary conversion. For
example:
Dim SomeValue ' Variant by default.
SomeValue = "17" ' SomeValue contains "17" (a two-
' character string).
SomeValue = SomeValue - 15 ' SomeValue now contains
' the
numeric value 2.
SomeValue = "U" & SomeValue ' SomeValue now contains
' "U2" (a two- character string).

While you can perform operations on Variant variables without much concern
for the kind of data they contain, there are some traps you must avoid.
If you perform arithmetic operations or functions on a Variant, the Variant
must contain something that is a number.

If you are concatenating strings, use the & operator instead of the + operator.

In addition to being able to act like the other standard data types, Variants can
also contain three special values: Empty, Null, and Error.

The Empty Value


Sometimes you need to know if a value has ever been assigned to a created
variable. A Variant variable has the Empty value before it is assigned a value.
The Empty value is a special value different from 0, a zero-length string (""), or
the Null value. You can test for the Empty value with the IsEmpty function:
If IsEmpty(Z) Then Z = 0

When a Variant contains the Empty value, you can use it in expressions; it is
treated as either 0 or a zero-length string, depending on the expression.
The Empty value disappears as soon as any value (including 0, a zero-length
string, or Null) is assigned to a Variant variable. You can set a Variant variable
back to Empty by assigning the keyword Empty to the Variant.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The Null Value
The Variant data type can contain another special value: Null. Null is commonly
used in database applications to indicate unknown or missing data. Because of
the way it is used in databases, Null has some unique characteristics:
Expressions involving Null always result in Null. Thus, Null is said to
"propagate" through expressions; if any part of the expression evaluates to
Null, the entire expression evaluates to Null.
Passing Null, a Variant containing Null, or an expression that evaluates to
Null as an argument to most functions causes the function to return Null.
Null values propagate through intrinsic functions that return Variant data
types.

You can also assign Null with the Null keyword:


Z = Null

You can use the IsNull function to test if a Variant variable contains Null:

If IsNull(X) And IsNull(Y) Then


Z = Null
Else
Z=0
End If

If you assign Null to a variable of any type other than Variant, a trappable error
occurs. Assigning Null to a Variant variable doesn't cause an error, and Null will
propagate through expressions involving Variant variables (though Null does
not propagate through certain functions). You can return Null from any
Function procedure with a Variant return value.
Variables are not set to Null unless you explicitly assign Null to them, so if you
don't use Null in your application, you don't have to write code that tests for and
handles it.

The Error Value


In a Variant, Error is a special value used to indicate that an error condition has
occurred in a procedure. However, unlike for other kinds of errors, normal
application-level error handling does not occur. This allows you, or the
application itself, to take some alternative based on the error value. Error values
are created by converting real numbers to error values using the CVErr
function.
If you have programmed in other languages, you're probably familiar with the
concept of arrays. Arrays allow you to refer to a series of variables by the same

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


name and to use a number (an index) to tell them apart. This helps you create
smaller and simpler code in many situations, because you can set up loops that
deal efficiently with any number of cases by using the index number. Arrays
have both upper and lower bounds, and the elements of the array are contiguous
within those bounds. Because Visual Basic allocates space for each index
number, avoid declaring an array larger than necessary.
Note The arrays discussed in this section are arrays of variables, declared in
code. They are different from the control arrays you specify by setting the Index
property of controls at design time. Arrays of variables are always contiguous;
unlike control arrays, you cannot load and unload elements from the middle of
the array.

All the elements in an array have the same data type. Of course, when the data
type is Variant, the individual elements may contain different kinds of data
(objects, strings, numbers, and so on). You can declare an array of any of the
fundamental data types, including user-defined types.
In Visual Basic there are two types of arrays: a fixed-size array which always
remains the same size, and a dynamic array whose size can change at run-time.
Dynamic arrays are discussed in more detail in the section "Dynamic Arrays"
later in this chapter.

Declaring Fixed-Size Arrays


There are three ways to declare a fixed-size array, depending on the scope you
want the array to have:
To create a public array, use the Public statement in the Declarations section of
a module to declare the array.
To create a module-level array, use the Private statement in the Declarations
section of a module to declare the array.
To create a local array, use the Private statement in a procedure to declare the
array.

Setting Upper and Lower Bounds


When declaring an array, follow the array name by the upper bound in
parentheses. The upper bound cannot exceed the range of a Long data type (-
2,147,483,648 to 2,147,483,647). For example, these array declarations can
appear in the Declarations section of a module:
Dim Counters(14) As Integer ' 15 elements.
Dim Sums(20) As Double ' 21 elements.

To create a public array, you simply use Public in place of Dim:


Public Counters(14) As Integer
Public Sums(20) As Double

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The same declarations within a procedure use Dim:
Dim Counters(14) As Integer
Dim Sums(20) As Double

The first declaration creates an array with 15 elements, with index numbers
running from 0 to 14. The second creates an array with 21 elements, with index
numbers running from 0 to 20. The default lower bound is 0.
To specify a lower bound, provide it explicitly (as a Long data type) using the To
keyword:
Dim Counters(1 To 15) As Integer
Dim Sums(100 To 120) As String

In the preceding declarations, the index numbers of Counters range from 1 to


15, and the index numbers of Sums range from 100 to 120.

Arrays that Contain Other Arrays


It's possible to create a Variant array, and populate it with other arrays of
different data types. The following code creates two arrays, one containing
integers and the other strings. It then declares a third Variant array and
populates it with the integer and string arrays.
Private Sub Command1_Click()
Dim intX As Integer ' Declare counter variable.
' Declare and populate an integer array.
Dim countersA(5) As Integer
For intX = 0 To 4
countersA(intX) = 5
Next intX
' Declare and populate a string array.
Dim countersB(5) As String
For intX = 0 To 4
countersB(intX) = "hello"
Next intX
Dim arrX(2) As Variant ' Declare a new two-member
' array.
arrX(1) = countersA() ' Populate the array with
' other
arrays.
arrX(2) = countersB()
MsgBox arrX(1)(2) ' Display a member of each
' array.
MsgBox arrX(2)(3)
End Sub

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Multidimensional Arrays
Sometimes you need to keep track of related information in an array. For
example, to keep track of each pixel on your computer screen, you need to refer
to its X and Y coordinates. This can be done using a multidimensional array to
store the values.
With Visual Basic, you can declare arrays of multiple dimensions. For example,
the following statement declares a two-dimensional 10-by-10 array within a
procedure:
Static MatrixA(9, 9) As Double

Either or both dimensions can be declared with explicit lower bounds:


Static MatrixA(1 To 10, 1 To 10) As Double

You can extend this to more than two dimensions. For example:
Dim MultiD(3, 1 To 10, 1 To 15)

This declaration creates an array that has three dimensions with sizes 4 by 10 by
15. The total number of elements is the product of these three dimensions, or
600.
Note When you start adding dimensions to an array, the total storage needed
by the array increases dramatically, so use multidimensional arrays with care.
Be especially careful with Variant arrays, because they are larger than other
data types.

Using Loops to Manipulate Arrays


You can efficiently process a multidimensional array by using nested For loops.
For example, these statements initialize every element in MatrixA to a value
based on its location in the array:
Dim I As Integer, J As Integer
Static MatrixA(1 To 10, 1 To 10) As Double
For I = 1 To 10
For J = 1 To 10
MatrixA(I, J) = I * 10 + J
Next J
Next I

Sometimes you may not know exactly how large to make an array. You may
want to have the capability of changing the size of the array at run time.
A dynamic array can be resized at any time. Dynamic arrays are among the
most flexible and convenient features in Visual Basic, and they help you to
manage memory efficiently. For example, you can use a large array for a short

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


time and then free up memory to the system when you're no longer using the
array.
The alternative is to declare an array with the largest possible size and then
ignore array elements you don't need. However, this approach, if overused,
might cause the operating environment to run low on memory.
To create a dynamic array
1. Declare the array with a Public statement (if you want the array to be public)
or Dim statement at the module level (if you want the array to be module
level), or a Static or Dim statement in a procedure (if you want the array to be
local). You declare the array as dynamic by giving it an empty dimension list.
Dim DynArray()

2. Allocate the actual number of elements with a ReDim statement.


ReDim DynArray(X + 1)

The ReDim statement can appear only in a procedure. Unlike the Dim and Static
statements, ReDim is an executable statement — it makes the application carry
out an action at run time.
The ReDim statement supports the same syntax used for fixed arrays. Each
ReDim can change the number of elements, as well as the lower and upper
bounds, for each dimension. However, the number of dimensions in the array
cannot change.
ReDim DynArray(4 to 12)

For example, the dynamic array Matrix1 is created by first declaring it at the
module level:
Dim Matrix1() As Integer

A procedure then allocates space for the array:


Sub CalcValuesNow ()
.
.
ReDim Matrix1(19, 29)
End Sub

The ReDim statement shown here allocates a matrix of 20 by 30 integers (at a


total size of 600 elements). Alternatively, the bounds of a dynamic array can be
set using variables:
ReDim Matrix1(X, Y)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Preserving the Contents of Dynamic Arrays
Each time you execute the ReDim statement, all the values currently stored in
the array are lost. Visual Basic resets the values to the Empty value (for Variant
arrays), to zero (for numeric arrays), to a zero-length string (for string arrays),
or to Nothing (for arrays of objects).
This is useful when you want to prepare the array for new data, or when you
want to shrink the size of the array to take up minimal memory. Sometimes you
may want to change the size of the array without losing the data in the array.
You can do this by using ReDim with the Preserve keyword. For example, you
can enlarge an array by one element without losing the values of the existing
elements using the UBound function to refer to the upper bound:
ReDim Preserve DynArray(UBound(DynArray) + 1)

Only the upper bound of the last dimension in a multidimensional array can be
changed when you use the Preserve keyword; if you change any of the other
dimensions, or the lower bound of the last dimension, a run-time error occurs.
Thus, you can use code like this:
ReDim Preserve Matrix(10, UBound(Matrix, 2) + 1)

But you cannot use this code:


ReDim Preserve Matrix(UBound(Matrix, 1) + 1, 10)

Sub Procedures:
A Sub procedure is a block of code that is executed in response to an event. By
breaking the code in a module into Sub procedures, it becomes much easier to
find or modify the code in your application.
The syntax for a Sub procedure is:
[Private|Public][Static]Sub procedurename (arguments)
statements
End Sub

Each time the procedure is called, the statements between Sub and End Sub are
executed. Sub procedures can be placed in standard modules, class modules, and
form modules. Sub procedures are by default Public in all modules, which
means they can be called from anywhere in the application.
The arguments for a procedure are like a variable declaration, declaring values
that are passed in from the calling procedure.

Operators:

There are three types of operators, namely

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


1. Arithmetic Operators(+, -, *, /, \, ^, Mod and &)

x\y makes integer division after rounding x and y to integers. 100 Mod 7 gives
the remainder when 100 is divided by 7. The & operator is used to concatenate two
strings. For eg.
"krishna" & "murthy" gives "Krishnamurthy". The + sign can also
be used to concatenate two strings.

2. Relational or Comparison Operators:(=, >, <, >=, <= and <>).

3. Logical Operators:(Not, And, Or and Xor)


The Xor operator returns a False value only when both the operands are either
True or False.

Hierarchy of Operators:

When different operators appear in an expression,


computation is done following the hierachy given below.

1. Exponential(^)
2. Equality(=)
3. Not
4. Negation(-)
5. Inequality(<>)
6. And
7. Multiplication and Division(* and /)
8. Less than(<)
9. Or
10. Integer Division(\)
11. Greater than
12. Xor
13. Mod
14. Less than or Equal to(<=)
15. Addition and Subtraction(+ and -)
16. Greater than or Equal to(>=)
17. String Concatenation(&)

Library Functions:

All the arithmetic and string functions supported by Gwbasic and Qbasic are
also supported by Visual Basic. A list of some important functions are given below:

1. Abs(x) returns the absolute value of x.


2. Exp(x) returns the xth power of the base of the natural log.
3. Log(x) returns the natural logarithm of x.
4. Sqr(x) returns the square root of x.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


5. Sin(x) returns the sine of the angle x (expressed in radians).
6. Cos(x) returns the cosine of x expressed in radians.
7. Tan(x) returns the tangent of x expressed in radians.
8. Atn(x) returns the angle in radians whose tangent is x
9. Lcase(alphabetic string) returns the string after converting
the upper case letters to lower case.
Lcase("ABCD") is returned as "abcd"
10. Str(number) converts a number to string.
str(1234) will return "1234"
11. val(numeric string) converts a numeric string to its value.
val("456.6") will return 456.6
12. Ucase(alphabetic string) converts lower case to upper case.
Ucase("abcd") is returned as "ABCD"

13. Len(string) returns the length of the string in terms of


the number of characters in it.
14. Left(string, n) returns n characters from the left end.
Left("abcdefgh",4) will return "abcd"
15. Right(string,n) returns n characters from the right end.
Right("abcdefgh",4) will return "efgh"
16. Mid(string, m, n) returns n characters starting from the
mth position.
Mid("abcdefgh", 4, 2) will return "de"
17. Instr(Tstring, Wstring) returns the position of the
Wstring in the Tstring if present, other-
returns zero. Instr("Krishnan", "nan")
returns 6.
18. Ltrim(string) removes any space on the left end of the string
19. Rtrim(string) removesy space on the right end of the string
20. Timeserial(hh,mm,ss) returns a time serial number given the
hour, minute and second.
21. cvdate("expression") returns the date when the expression
gives a number called the datenumber
which is the number of days elapsed
from 31/12/1899. Fo eg.
cvdate("35678") returns 9/5/97
Statements:

A statement is a construct which gives complete meaning to


the computer. It is analogous to a sentence in a spoken
language, which gives complete meaning to the humans. There are
different kinds of statements for doing different jobs. We will consider the
Assignment Statement and the different control Statements.

The general form of an Assignment Statement is

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Variable = Expression or Value

This statement is used to assign a value to a variable or compute


any expression and store the computed value in a variable.

For example the statement

Interest = Principal * Rate * years/100

instructs the computer to compute the expression on the r.h.s. of the assignment
operator(=) and store it in the variable on the l.h.s.

Comment Statement:

Comments constitute the documentation part of a program. A


program with meaningful comments makes it readable by any ser.
Any text which starts with the symbol ' is a comment. One can
also use the reserved word REM before writing the comments.

In order to implement complex logic, we need control


Statements. The following are the Control Statements available
in Visual Basic.

1. If-Then-Else
2. If-Then-Elself
3. Select Case
4. Do While
5. Do Loop While
6. Do Until
7. For Next
8. While-Wend
The general form of If Then Else Statement is

If <logical expression> Then


---------
----------
[Else
---------
----------]
End If

Else clause is only optional. One possibl drawack with an If-Then-Else statement is
that if the first condition is false, VB blindly follows the second group of
instructions. If you don't want this to happen, you have to specify a condition for
the second set of instructions. To do this, you have to use an If-Then-Elself

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Statement. The general form of If-Then-Else Statement is

If <condition1> Then
Instrctions1
Elself <condition2> THen
Instructions2
End If

In this case if condition1 is true the first set of instrctions


are obeyed. If condition1 is false it tests the condition2.
If condition2 is true, it obeys the second set of instructions. If condition2 also is false
the control comes out of the If loop withou doing anything.

For checking multiple conditions, one can use multiple Elself as


shown below:

If <condition1> Then
instrctions1
Elself <condition2> Then
instructions2
Elself <condition3> Then
instructions3
End If

If you want to make sure that at least one set of instructions


are followed, add an else statement as shown below:

If <condition1> Then
instrctions1
Elself <condition2> Then
instructions2
Elself <condition3> Then
instructions3
Else
instruction default
End If

The Select Case Statement:

If you want to make a choice among multiple lternatives,


the Select Case Statement can be used. It looks as below:

Select Case <variable>


Case x
instructions1
Case Y

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


instructions2
Case Z
instructions3
End Select

This statement tells the computer to check the value of X and if its value is equal to
the value of the variable, then follow instructions1 and come out. If not try for y
and then try for z. If none of the values equal the value of variable, do nothing.
One drawback with the Select statement is that you have to give exact values after
Case and you can't give a Case as

Case age > 15

You can give only as Case age = 15


In order to make sure that the computer follows at least one instrctions set
before coming out, write the Select Case statement with an Else Clause as shown
below:

Select Case <variable>


Case x
instructions1
Case Y
instructions2
Case Z
instructions3
Case Else
Instructionsdefault
End Select

The Do-While Loop:

In order to repeatedly perform a set of statements based on some condition, the


Do-While Loop is used. The general form is

Do While <condition>
------
------
Loop

The set of statements bracketed between the words Do While and Loop will be
repeatedly executed so long as the condition is true. If the condition becomes
false, the control will come out of the loop. If the condition never becomes false the
computer will be caught in an endless loop and will hang on. Such a condition
must be avoided.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The Do-Until Loop:

There is another looping construct called the Do Until Loop. The general form is

Do Until <condition>
------
------
Loop

In this case the looping will continue until the condition is false. Once the
condition becomes true, the control will come out of the loop.

The Do Loop Until:

If you want to ensure that the loop is executed at least once irrespective of the true
or false value of the condition, the Do Loop Until is used. The general form is

Do
------
-------
Loop Until <ondition>

in this case the condition is checked only after the Loop statements are
executed once. If the condition is false the looping continues and if the condition
is true, the control comes out of the loop.

The For-Next Loop:

If you know exactly the number of times a particular segmentof statements are to
be executed, the For-Next statement is used.The general form is

For variable = startvalue To endvalue [ step stepvalue]


------
------
Next variable

If the stepvalue is omitted, the start value is incremented by unity at the end of
every loop. The step value can be negative. In that case the endvalue must be less
than the start value.

For example one can write For statements as


For i = 1 to 100 step 5
-----
-----
next i

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


For i = 100 to 10 step -5
-----
-----
next i

Quick Exits from Do and For Loops:

A Do Loop continues running until a certain condition becomes True or


False. A For Next Loop continues running until it finishes counting.
Sometimes the problem logic may demand premature exits from the loop
based on certain condition. In that case one uses the Exit statement as shown
below.

Do while condition
-----
if <condition> Then Exit Do
------
Loop
For variable = startvalue to endvalue
------
if <condition> Then Exit For
-------
Next variable

While-Wend:

The While-Wend loop executes a block of statements while a condition is


true. The While-Wend loop has the following syntax.
While condition
Statements block
Wend
The following While-Wend loop prompts the user to enter numeric data.
The user can type a negative value to indicate that all values are entered.

number = 0
while number => 0
total = total + number
number = inputbox(“enter another number”)
wend

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Procedures and Functions:

In Visual Basic, it's useful to distinguish between two types of Sub procedures,
general procedures and event procedures.

General Procedures
A general procedure tells the application how to perform a specific task. Once a
general procedure is defined, it must be specifically invoked by the application.
By contrast, an event procedure remains idle until called upon to respond to
events caused by the user or triggered by the system.
Why create general procedures? One reason is that several different event
procedures might need the same actions performed. A good programming
strategy is to put common statements in a separate procedure (a general
procedure) and have your event procedures call it. This eliminates the need to
duplicate code and also makes the application easier to maintain.

Event Procedures
When an object in Visual Basic recognizes that an event has occurred, it
automatically invokes the event procedure using the name corresponding to the
event. Because the name establishes an association between the object and the
code, event procedures are said to be attached to forms and controls.
An event procedure for a control combines the control's actual name
(specified in the Name property), an underscore (_), and the event name. For
instance, if you want a command button named cmdPlay to invoke an event
procedure when it is clicked, use the procedure cmdPlay_Click.
An event procedure for a form combines the word "Form," an underscore,
and the event name. If you want a form to invoke an event procedure when it
is clicked, use the procedure Form_Click. (Like controls, forms do have
unique names, but they are not used in the names of event procedures.) If you
are using the MDI form, the event procedure combines the word
"MDIForm," an underscore, and the event name, as in MDIForm_Load.

All event procedures use the same general syntax.


Syntax for a control event Syntax for a form event

Private Sub controlname_eventname (arguments )


statementsEnd Sub Private Sub Form_eventname (arguments)
statements
End Sub

Although you can write event procedures from scratch, it's easier to use the code
procedures provided by Visual Basic, which automatically include the correct
procedure names. You can select a template in the Code Editor window by

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


selecting an object from the Object box and then selecting a procedure from the
Procedure box.
It's also a good idea to set the Name property of your controls before you start
writing event procedures for them. If you change the name of a control after
attaching a procedure to it, you must also change the name of the procedure to
match the new name of the control. Otherwise, Visual Basic won't be able to
match the control to the procedure. When a procedure name does not match a
control name, it becomes a general procedure.
Visual Basic includes built-in, or intrinsic functions, like Sqr, Cos or Chr. In
addition, you can use the Function statement to write your own Function
procedures.
The syntax for a Function procedure is:
[Private|Public][Static]Function procedurename (arguments) [As type]
statements
End Function

Like a Sub procedure, a Function procedure is a separate procedure that can


take arguments, perform a series of statements, and change the value of its
arguments. Unlike a Sub procedure, a Function procedure can return a value to
the calling procedure. There are three differences between Sub and Function
procedures:
Generally, you call a function by including the function procedure name and
arguments on the right side of a larger statement or expression (returnvalue =
function()).
Function procedures have data types, just as variables do. This determines the
type of the return value. (In the absence of an As clause, the type is the default
Variant type.)
You return a value by assigning it to the procedurename itself. When the
Function procedure returns a value, this value can then become part of a
larger expression.

For example, you could write a function that calculates the third side, or
hypotenuse, of a right triangle, given the values for the other two sides:
Function Hypotenuse (A As Integer, B As Integer) _
As String
Hypotenuse = Sqr(A ^ 2 + B ^ 2)
End Function

You call a Function procedure the same way you call any of the built-in
functions in Visual Basic:
Label1.Caption = Hypotenuse(CInt(Text1.Text), _
CInt(Text2.Text))
strX = Hypotenuse(Width, Height)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Creating New Procedures
To create a new general procedure
Type a procedure heading in the Code window and press ENTER. The
procedure heading can be as simple as Sub or Function followed by a name.
For example, you can enter either of the following:
Sub UpdateForm ()
Function GetCoord ()

Visual Basic responds by completing the template for the new procedure.
Selecting Existing Procedures
To view a procedure in the current module
To view an existing general procedure, select "(General)" from the Object box
in the Code window, and then select the procedure in the Procedure box.
– or –
To view an event procedure, select the appropriate object from the Object box
in the Code window, and then select the event in the Procedure box.

To view a procedure in another module


1 From the View menu, choose Object Browser.
2 Select the project from the Project/Library box.
3 Select the module from the Classes list, and the procedure from the Members
of list.
4 Choose View Definition.

Calling Procedures
The techniques for calling procedures vary, depending on the type of procedure,
where it's located, and how it's used in your application. The following sections
describe how to call Sub and Function procedures.

Calling Sub Procedures


A Sub procedure differs from a Function procedure in that a Sub procedure
cannot be called by using its name within an expression. A call to a Sub is a
stand-alone statement. Also, a Sub does not return a value in its name as does a
function. However, like a Function, a Sub can modify the values of any variables
passed to it.
There are two ways to call a Sub procedure:
' Both of these statements call a Sub named MyProc.
Call MyProc (FirstArgument, SecondArgument)
MyProc FirstArgument, SecondArgument

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Note that when you use the Call syntax, arguments must be enclosed in
parentheses. If you omit the Call keyword, you must also omit the parentheses
around the arguments.

Calling Function Procedures


Usually, you call a function procedure you've written yourself the same way you
call an intrinsic Visual Basic function like Abs; that is, by using its name in an
expression:
' All of the following statements would call a function
' named ToDec.
Print 10 * ToDec
X = ToDec
If ToDec = 10 Then Debug.Print "Out of Range"
X = AnotherFunction(10 * ToDec)

It's also possible to call a function just like you would call a Sub procedure. The
following statements both call the same function:
Call Year(Now)
Year Now

When you call a function this way, Visual Basic throws away the return value.

Calling Procedures in Other Modules


Public procedures in other modules can be called from anywhere in the project.
You might need to specify the module that contains the procedure you're calling.
The techniques for doing this vary, depending on whether the procedure is
located in a form, class, or standard module.

Procedures in Forms
All calls from outside the form module must point to the form module containing
the procedure. If a procedure named SomeSub is in a form module called
Form1, then you can call the procedure in Form1 by using this statement:
Call Form1.SomeSub(arguments)
Procedures in Class Modules
Like calling a procedure in a form, calling a procedure in a class module
requires that the call to the procedure be qualified with a variable that points to
an instance of the class. For example, DemoClass is an instance of a class named
Class1:
Dim DemoClass as New Class1
DemoClass.SomeSub

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


However, unlike a form, the class name cannot be used as the qualifier when
referencing an instance of the class. The instance of the class must be first be
declared as an object variable (in this case, DemoClass) and referenced by the
variable name.

Procedures in Standard Modules


If a procedure name is unique, you don't need to include the module name in the
call. A call from inside or outside the module will refer to that unique procedure.
A procedure is unique if it appears only in one place.
If two or more modules contain a procedure with the same name, you may need
to qualify it with the module name. A call to a common procedure from the same
module runs the procedure in that module. For example, with a procedure
named CommonName in Module1 and Module2, a call to CommonName from
Module2 will run the CommonName procedure in Module2, not the
CommonName procedure in Module1.
A call to a common procedure name from another module must specify the
intended module. For example, if you want to call the CommonName procedure
in Module2 from Module1, use:
Module2.CommonName(arguments)

Usually the code in a procedure needs some information about the state of the
program to do its job. This information consists of variables passed to the
procedure when it is called. When a variable is passed to a procedure, it is called
an argument.

Argument Data Types


The arguments for procedures you write have the Variant data type by default.
However, you can declare other data types for arguments. For example, the
following function accepts a string and an integer:
Function WhatsForLunch(WeekDay As String, Hour _
As Integer) As String
' Returns a lunch menu based on the day and time.
If WeekDay = "Friday" then
WhatsForLunch = "Fish"
Else
WhatsForLunch = "Chicken"
End If
If Hour > 4 Then WhatsForLunch = "Too late"
End Function

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Passing Arguments By Value
Only a copy of a variable is passed when an argument is passed by value. If the
procedure changes the value, the change affects only the copy and not the
variable itself. Use the ByVal keyword to indicate an argument passed by value.
For example:
Sub PostAccounts(ByVal intAcctNum as Integer)
.
. ' Place statements here.
.
End Sub

Passing Arguments By Reference


Passing arguments by reference gives the procedure access to the actual variable
contents in its memory address location. As a result, the variable's value can be
permanently changed by the procedure to which it is passed. Passing by
reference is the default in Visual Basic.
If you specify a data type for an argument passed by reference, you must pass a
value of that type for the argument. You can work around this by passing an
expression, rather than a data type, for an argument. Visual Basic evaluates an
expression and passes it as the required type if it can.
The simplest way to turn a variable into an expression is to enclose it in
parentheses. For example, to pass a variable declared as an integer to a
procedure expecting a string as an argument, you would do the following:
Sub CallingProcedure()
Dim intX As Integer
intX = 12 * 3
Foo(intX)
End Sub

Sub Foo(Bar As String)


MsgBox Bar 'The value of Bar is the string "36".
End Sub

Using Optional Arguments


You can specify arguments to a procedure as optional by placing the Optional
keyword in the argument list. If you specify an optional argument, all
subsequent arguments in the argument list must also be optional and declared

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


with the Optional keyword. The two pieces of sample code below assume there is
a form with a command button and list box.
For example, this code provides all optional arguments:
Dim strName As String
Dim varAddress As Variant

Sub ListText(Optional x As String, Optional y _


As Variant)
List1.AddItem x
List1.AddItem y
End Sub

Private Sub Command1_Click()


strName = "yourname"
varAddress = 12345 ' Both arguments are provided.
Call ListText(strName, varAddress)
End Sub

This code, however, does not provide all optional arguments:


Dim strName As String
Dim varAddress As Variant

Sub ListText(x As String, Optional y As Variant)


List1.AddItem x
If Not IsMissing(y) Then
List1.AddItem y
End If
End Sub

Private Sub Command1_Click()


strName = "yourname" ' Second argument is not
' provided.
Call ListText(strName)
End Sub

In the case where an optional argument is not provided, the argument is actually
assigned as a variant with the value of Empty. The example above shows how to
test for missing optional arguments using the IsMissing function.

Providing a Default for an Optional Argument


It's also possible to specify a default value for an optional argument. The
following example returns a default value if the optional argument isn't passed
to the function procedure:
Sub ListText(x As String, Optional y As _

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Variant = 12345)
List1.AddItem x
List1.AddItem y
End Sub

Private Sub Command1_Click()


strName = "yourname" ' Second argument is not
' provided.
Call ListText(strName) ' Adds "yourname" and
' "12345".
End Sub

Using an Indefinite Number of Arguments


Generally, the number of arguments in the procedure call must be the same as in
the procedure specification. Using the ParamArray keyword allows you to
specify that a procedure will accept an arbitrary number of arguments. This
allows you to write functions like Sum:
Dim x As Variant
Dim y As Integer
Dim intSum As Integer

Sub Sum(ParamArray intNums())


For Each x In intNums
y=y+x
Next x
intSum = y
End Sub

Private Sub Command1_Click()


Sum 1, 3, 5, 7, 8
List1.AddItem intSum
End Sub

Creating Simpler Statements with Named Arguments


For many built-in functions, statements, and methods, Visual Basic provides the
option of using named arguments as a shortcut for typing argument values. With
named arguments, you can provide any or all of the arguments, in any order, by
assigning a value to the named argument. You do this by typing the argument
name plus a colon followed by an equal sign and the value ( MyArgument:=
"SomeValue") and placing that assignment in any sequence delimited by
commas. Notice that the arguments in the following example are in the reverse
order of the expected arguments:
Function ListText(strName As String, Optional varAddress As Variant)
List1.AddItem strName

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


List2.AddItem varAddress
End Sub

Private Sub Command1_Click()


ListText varAddress:=12345, strName:="Your Name"
End Sub

This is especially useful if your procedures have several optional arguments that
you do not always need to specify.

Determining Support for Named Arguments


To determine which functions, statements, and methods support named
arguments, use the AutoQuickInfo feature in the Code window, check the Object
Browser, or see the Language Reference in Books Online. Consider the following
when working with named arguments:
Named arguments are not supported by methods on objects in the Visual
Basic (VB) object library. They are supported by all language keywords in the
Visual Basic for applications (VBA) object library, and by methods in the data
access (DAO) object library.
In syntax, named arguments are shown as bold and italic. All other
arguments are shown in italic only.

Important You cannot use named arguments to avoid entering required


arguments. You can omit only the optional arguments. For Visual Basic (VB)
and Visual Basic for applications (VBA) object libraries, the Object Browser
encloses optional arguments with square brackets [ ].
x------------------------------------------------------x

Visual Basic-6
19. Classes and Objects
Objects

When you create an application in Visual Basic, you work with objects. You can use
objects provided by Visual Basic — such as controls, forms, and data access objects.
You can also control other applications' objects from within your Visual Basic
application. You can even create your own objects, and define additional properties
and methods for them.
An object is a combination of code and data that can be treated as a unit. An
object can be a piece of an application, like a control or a form. An entire
application can also be an object. The following table describes examples of the
types of objects you can use in Visual Basic.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Example Description

Command Button Controls on a form such as command buttons


And frames are objects.
Form Each Form in a Visual Basic Project is a
Separate object
Database Databases are objects and contain other objects
Like fields and indexes.
Chart A chart in Microsoft Excel is an object.

Where do Objects Come From?


Each object in Visual Basic is defined by a class. To understand the relationship
between an object and its class, think of cookie cutters and cookies. The cookie
cutter is the class. It defines the characteristics of each cookie — for instance,
size and shape. The class is used to create objects. The objects are the cookies.
Two examples of the relationship between classes and objects in Visual Basic
may make this clearer.
The controls on the Toolbox in Visual Basic represent classes. The object
known as a control doesn't exist until you draw it on a form. When you create
a control, you're creating a copy or instance of the control class. That instance
of the class is the object you refer to in your application.
The form you work with at design time is a class. At run time, Visual Basic
creates an instance of the form's class

All objects are created as identical copies of their class. Once they exist as
individual objects, their properties can be changed. For example, if you draw
three command buttons on a form, each command button object is an instance of
the CommandButton class. Each object shares a common set of characteristics
and capabilities (properties, methods, and events), defined by the class.
However, each has its own name, can be separately enabled and disabled, can be
placed in a different location on the form, and so on.

An object provides code you don't have to write. For example, you could create
your own File Open and File Save dialog boxes, but you don't have to. Instead,
you can use the common dialog control (an object) provided by Visual Basic.
You could write your own scheduling and resource management code, but you
don't have to. Instead, you can use the Calendar, Resources, and Task objects
provided by Microsoft project.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Visual Basic Can Combine Objects from Other Sources
Visual Basic provides the tools to allow you to combine objects from different
sources. You can now build custom solutions combining the most powerful
features of Visual Basic and applications that support Automation (formerly
known as OLE Automation). Automation is a feature of the Component Object
Model (COM), an industry standard used by applications to expose objects to
development tools and other applications.
You can build applications by tying together intrinsic Visual Basic controls, and
you can also use objects provided by other applications. Consider placing these
objects on a Visual Basic form:
A Microsoft Excel Chart object
A Microsoft Excel Worksheet object
A Microsoft Word Document object

Visual Basic objects support properties, methods, and events. In Visual Basic, an
object's data (settings or attributes) are called properties, while the various
procedures that can operate on the object are called its methods. An event is an
action recognized by an object, such as clicking a mouse or pressing a key, and
you can write code to respond to that event.
You can change an object's characteristics by changing its properties. Consider
a radio: One property of a radio is its volume. In Visual Basic, you might say
that a radio has a "Volume" property that you can adjust by changing its value.
Assume you can set the volume of the radio from 0 to 10. If you could control a
radio with Visual Basic, you might write code in a procedure that changes the
value of the "Volume" property from 3 to 5 to make the radio play louder:
Radio.Volume = 5

In addition to properties, objects have methods. Methods are a part of objects


just as properties are. Generally, methods are actions you want to perform,
while properties are the attributes you set or retrieve. For example, you dial a
telephone to make a call. You might say that telephones have a "Dial" method,
and you could use this syntax to dial the seven-digit number 5551111:
Phone.Dial 5551111

Objects also have events. Events are triggered when some aspect of the object is
changed. For example, a radio might have a "VolumeChange" event. A
telephone might have a "Ring" event.

Controlling Objects with Their Properties


Individual properties vary as to when you can set or get their values. Some
properties can be set at design time. You can use the Properties window to set
the value of these properties without writing any code at all. Some properties are

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


not available at design time; therefore, you must write code to set those
properties at run time.
Properties that you can set and get at run time are called read-write properties.
Properties you can only read at run time are called read-only properties.

Setting Property Values


You set the value of a property when you want to change the appearance or
behavior of an object. For example, you change the Text property of a text box
control to change the contents of the text box.
To set the value of a property, use the following syntax:
object.property = expression

The following statements demonstrate how you set properties:


Text1.Top = 200 ' Sets the Top property to 200 twips.
Text1.Visible = True ' Displays the text box.
Text1.Text = "hello" ' Displays'hello'in the text box.

Getting Property Values


You get the value of a property when you want to find the state of an object
before your code performs additional actions (such as assigning the value to
another object). For example, you can return the Text property of a text box
control to determine the contents of the text box before running code that might
change the value.
In most cases, to get the value of a property, you use the following syntax:
variable = object.property

You can also get a property value as part of a more complex expression, without
assigning the property to a variable. In the following code example, the Top
property of the new member of a control array is calculated as the Top property
of the previous member, plus 400:
Private Sub cmdAdd_Click()
' [statements]
optButton(n).Top = optButton(n-1).Top + 400
' [statements]
End Sub

Tip If you're going to use the value of a property more than once, your code
will run faster if you store the value in a variable.

Performing Actions with Methods

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Methods can affect the values of properties. For example, in the radio analogy,
the SetVolume method changes the Volume property. Similarly, in Visual Basic,
list boxes have a List property, which can be changed with the Clear and
AddItem methods.

Using Methods in Code


When you use a method in code, how you write the statement depends on how
many arguments the method requires, and whether the method returns a value.
When a method doesn't take arguments, you write the code using the following
syntax:
object.method

In this example, the Refresh method repaints the picture box:


Picture1.Refresh ' Forces a repaint of the control.

Some methods, such as the Refresh method, don't have arguments and don't
return values.
If the method takes more than one argument, you separate the arguments with a
comma. For example, the Circle method uses arguments specifying the location,
radius, and color of a circle on a form:
' Draw a blue circle with a 1200-twip radius.
Form1.Circle (1600, 1800), 1200, vbBlue

If you keep the return value of a method, you must enclose the arguments in
parentheses. For example, the GetData method returns a picture from the
Clipboard:
Picture = Clipboard.GetData (vbCFBitmap)

If there is no return value, the arguments appear without parentheses. For


example, the AddItem method doesn't return a value:
List1.AddItem "yourname" ' Adds the text 'yourname'
' to a list box.

When you put two command buttons on a form, they are separate objects with
distinct Name property settings (Command1 and Command2), but they share the
same class — CommandButton.
They also share the characteristic that they're on the same form. You've seen
earlier in this chapter that a control on a form is also contained by the form.
This puts controls in a hierarchy. To reference a control you may have to
reference the form first, in the same way you may have to dial a country code or
area code before you can reach a particular phone number.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The two command buttons also share the characteristic that they're controls. All
controls have common characteristics that make them different from forms and
other objects in the Visual Basic environment. The following sections explain
how Visual Basic uses collections to group objects that are related.

Object Hierarchies
An object hierarchy provides the organization that determines how objects are
related to each other, and how you can access them. In most cases, you don't
need to concern yourself with the Visual Basic object hierarchy. However:
When manipulating another application's objects, you should be familiar with
that application's object hierarchy. For information on navigating object
hierarchies, see "Programming with Components."
When working with data access objects, you should be familiar with the Data
Access Object hierarchy, as described in the Guide to Data Access Objects in
the Professional Features book, included with the Visual Basic, Professional
and Enterprise Editions.

Working with Collections of Objects


Collection objects have their own properties and methods. The objects in a
collection object are referred to as members of the collection. Each member of
the collection is numbered sequentially beginning at 0; this is the member's index
number. For example, the Controls collection contains all the controls on a given
form, as shown in Figure 5.10. You can use collections to simplify code if you
need to perform the same operation on all the objects in a collection.
For example, the following code scrolls through the Controls collection and lists
each member's name in a list box.
For Each Control In Form1.Controls
' For each control, add its name to a list box.
List1.AddItem Control.Name
Next Control

Applying Properties and Methods to Collection Members


There are two general techniques you can use to address a member of a
collection object:
Specify the name of the member. The following expressions are equivalent:
Controls("List1")
Controls!List1

Use the index number of the member:


Controls(3)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Once you're able to address all the members collectively, and single members
individually, you can apply properties and methods using either approach:
' Set the Top property of the list box control to 200.
Controls!List1.Top = 200
– or –
For Each Control In Form1.Controls()
' Set the Top property of each member to 200.
Control.Top = 200
Next Control

Objects That Contain Other Objects


Some objects in Visual Basic contain other objects. For example, a form usually
contains one or more controls. The advantage of having objects as containers for
other objects is that you can refer to the container in your code to make it clear
which object you want to use.

Common Collections in Visual Basic


JThere are some common cases in Visual Basic where one object contains other
objects. The following table briefly describes the most commonly used collections
in Visual Basic.
Collection Description

Forms Contains loaded forms.


Controls Contains controls on a form.
Printers Contains the available Printer objects.

You can also implement object containment in Visual Basic.

The Container Property


JYou can use the Container property to change an object's container within a
form. The following controls can contain other controls:
Frame control
Picture box control
Toolbar control (Professional and Enterprise editions only)

JThis example demonstrates moving a command button around from container


to container on a form. Open a new project, and draw a frame control, picture
box control and a command button on the form.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


TJhe following code in the form's click event increments a counter variable, and
uses a Select Case loop to rotate the command button from container to
container.
Private Sub Form_Click()
Static intX as Integer
Select Case intX
Case 0
Set Command1.Container = Picture1
Command1.Top= 0
Command1.Left= 0

Case 1
Set Command1.Container = Frame1
Command1.Top= 0
Command1.Left= 0

Case 2
Set Command1.Container = Form1
Command1.Top= 0
Command1.Left= 0

End Select
intX = intX + 1
End Sub

Communicating Between Objects


In addition to using and creating objects within Visual Basic, you can
communicate with other applications and manipulate their objects from within
your application. The ability to share data between applications is one of the key
features of the Microsoft Windows operating system. With Visual Basic, you
have great flexibility in how you can communicate with other applications.

The easiest way to create an object is to double-click a control in the Toolbox.


However, to realize the full benefit of all the objects available in Visual Basic and
from other applications, you can use Visual Basic's programmability features to
create objects at run time.
You can create references to an object with object variables.
You can create your own objects "from scratch" with class modules.
You can create your own collections with the Collection object.

Using Object Variables

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


In addition to storing values, a variable can refer to an object. You assign an
object to a variable for the same reasons you assign any value to a variable:
Variable names are often shorter and easier to remember than the values they
contain (or, in this case, the objects they refer to).
Variables can be changed to refer to other objects while your code is running.
Referring to a variable that contains an object is more efficient than
repeatedly referring to the object itself.

Using an object variable is similar to using a conventional variable, but with one
additional step — assigning an object to the variable:
First you declare it:
Dim variable As class

Then you assign an object to it:


Set variable = object

Declaring Object Variables


You declare an object variable in the same way you declare other variables, with
Dim, ReDim, Static, Private, or Public. The only differences are the optional
New keyword and the class argument; both of these are discussed later in this
chapter. The syntax is:
{Dim | ReDim | Static | Private | Public} variable As [New] class

For example, you can declare an object variable that refers to a form in the
application called frmMain:
Dim FormVar As New frmMain ' Declare an object
' variable of type
frmMain.

You can also declare an object variable that can refer to any form in the
application:
Dim anyForm As Form ' Generic form variable.

Similarly, you can declare an object variable that can refer to any text box in
your application:
Dim anyText As TextBox ' Can refer to any text box
' (but only a text
box).

You can also declare an object variable that can refer to a control of any type:
Dim anyControl As Control ' Generic control variable.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Notice that you can declare a form variable that refers to a specific form in the
application, but you cannot declare a control variable that refers to a particular
control. You can declare a control variable that can refer to a specific type of
control (such as TextBox or ListBox), but not to one particular control of that
type (such as txtEntry or List1). However, you can assign a particular control to
a variable of that type. For example, for a form with a list box called lstSample,
you could write:
Dim objDemo As ListBox
Set objDemo = lstSample

Assigning Object Variables


You assign an object to an object variable with the Set statement:
Set variable = object

Use the Set statement whenever you want an object variable to refer to an
object.
Sometimes you may use object variables, and particularly control variables,
simply to shorten the code you have to type. For example, you might write code
like this:
If frmAccountDisplay!txtAccountBalance.Text < 0 Then
frmAccountDisplay!txtAccountBalance.BackColor = 0
frmAccountDisplay!txtAccountBalance.ForeColor = 255
End If

You can shorten this code significantly if you use a control variable:
Dim Bal As TextBox
Set Bal = frmAccountDisplay!txtAccountBalance
If Bal.Text < 0 Then
Bal.BackColor = 0
Bal.ForeColor = 255
End If
Specific and Generic Object Types
Specific object variables must refer to one specific type of object or class. A
specific form variable can refer to only one form in the application (though it
can refer to one of many instances of that form). Similarly, a specific control
variable can refer to only one particular type of control in your application, such
as TextBox or ListBox. To see an example, open a new project and place a text
box on a form. Add the following code to the form:
Private Sub Form_Click()
Dim anyText As TextBox
Set anyText = Text1

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


anyText.Text = "Hello"
End Sub

Run the application, and click the form. The Text property of the text box will
be changed to "Hello."
Generic object variables can refer to one of many specific types of objects. A
generic form variable, for example, can refer to any form in an application; a
generic control variable can refer to any control on any form in an application.
To see an example, open a new project and place several frame, label, and
command button controls on a form, in any order. Add the following code to the
form:
Private Sub Form_Click()
Dim anyControl As Control
Set anyControl = Form1.Controls(3)
anyControl.Caption = "Hello"
End Sub

Run the application, and click the form. The caption of the control you placed
third in sequence on the form will be changed to "Hello."
There are four generic object types in Visual Basic:
Generic Object
Type Object referenced

Form Any form in the application (including MDI children and the MDI
form).
Control Any control in your application.
MDIForm The MDI form in the application (if your application has one).
Object Any object.

Generic object variables are useful when you don't know the specific type of
object a variable will refer to at run time. For example, if you want to write code
that can operate on any form in the application, you must use a generic form
variable.
Note Because there can be only one MDI form in the application, there is no
need to use the generic MDIForm type. Instead, you can use the specific
MDIForm type (MDIForm1, or whatever you specified for the Name property of
the MDI form) whenever you need to declare a form variable that refers to the
MDI form. In fact, because Visual Basic can resolve references to properties and
methods of specific form types before you run your application, you should
always use the specific MDIForm type.

The generic MDIForm type is provided only for completeness; should a future
version of Visual Basic allow multiple MDI forms in a single application, it
might become useful.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Forms as Objects
Forms are most often used to make up the interface of an application, but
they're also objects that can be called by other modules in your application.
Forms are closely related to class modules. The major difference between the
two is that forms can be visible objects, whereas class modules have no visible
interface.

Adding Custom Methods and Properties


You can add custom methods and properties to forms and access them from
other modules in your application. To create a new method for a form, add a
procedure declared using Public.
' Custom method on Form1
Public Sub LateJobsCount()
.
. ' <statements>
.
End Sub

You can call the LateJobsCount procedure from another module using this
statement:
Form1.LateJobsCount

Creating a new property for a form can be as simple as declaring a public


variable in the form module:
Public IDNumber As Integer

You can set and return the value of IDNumber on Form1 from another module
using these two statements:
Form1.IDNumber = 3
Text1.Text = Form1.IDNumber

You can also use Property procedures to add custom properties to a form.

Note You can call a variable, a custom method, or set a custom property on a
form without loading the form. This allows you to run code on a form without
loading it into memory. Also, referencing a control without referencing one of its
properties or methods does not load the form.
Using the New Keyword
Use the New keyword to create a new object as defined by its class. New can be
used to create instances of forms, classes defined in class modules, and
collections.

Using the New Keyword with Forms

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Each form you create at design time is a class. The New keyword can be used to
create new instances of that class. To see how this works, draw a command
button and several other controls on a form. Set the form's Name property to
Sample in the Properties window. Add the following code to your command
button's Click event procedure:
Dim x As New Sample
x.Show

Run the application, and click the command button several times. Move the
front-most form aside. Because a form is a class with a visible interface, you can
see the additional copies. Each form has the same controls, in the same positions
as on the form at design time.
Note To make a form variable and an instance of the loaded form persist, use a
Static or Public variable instead of a local variable.

You can also use New with the Set statement. Try the following code in a
command button's Click event procedure:
Dim f As Form1
Set f = New Form1
f.Caption = "hello"
f.Show

Using New with the Set statement is faster and is the recommended method.

Using the New Keyword with Other Objects


The New keyword can be used to create collections and objects from the classes
you define in class modules. To see how this works, try the following example.
This example demonstrates how the New keyword creates instances of a class.
Open a new project, and draw a command button on Form1. From the Project
menu, choose Add Class Module to add a class module to the project. Set the
class module's Name property to ShowMe.
The following code in the Form1 module creates a new instance of the class
ShowMe, and calls the procedure contained in the class module.
Public clsNew As ShowMe
Private Sub Command1_Click()
Set clsNew = New ShowMe
clsNew.ShowFrm
End Sub

The ShowFrm procedure in the class module creates a new instance of the class
Form1, shows the form, and then minimizes it.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Sub ShowFrm()
Dim frmNew As Form1
Set frmNew = New Form1
frmNew.Show
frmNew.WindowState = 1
End Sub

To use the example, run the application, and click the command button several
times. You'll see a minimized form icon appear on your desktop as each new
instance of the ShowMe class is created.

Freeing References to Objects


Each object uses memory and system resources. It is good programming practice
to release these resources when you are no longer using an object.
Use Unload to unload a form or control from memory.
Use Nothing to release resources used by an object variable. Assign Nothing to
an object variable with the Set statement.

Passing Objects to Procedures


You can pass objects to procedures in Visual Basic. In the following code
example, it's assumed that there is a command button on a form:
Private Sub Command1_Click()
' Calls the Demo sub, and passes the form to it.
Demo Form1
End Sub

Private Sub Demo(x As Form1)


' Centers the form on the screen.
x.Left = (Screen.Width - x.Width) / 2
End Sub

It's also possible to pass an object to an argument by reference and then, inside
the procedure, set the argument to a new object. To see how this works, open a
project, and insert a second form. Place a picture box control on each form. The
following table shows the property settings that need changes:

Object Property Setting

Picture box on Name Picture2


Form2 Picture c:\vb\icons\arrows\arw01dn.ico

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The Form1_Click event procedure calls the GetPicture procedure in Form2, and
passes the empty picture box to it.
Private Sub Form_Click()
Form2.GetPicture Picture1
End Sub

The GetPicture procedure in Form2 assigns the Picture property of the picture
box on Form2 to the empty picture box on Form1.
Private objX As PictureBox
Public Sub GetPicture(x As PictureBox)
' Assign the passed-in picture box to an object
' variable.
Set objX = x
' Assign the value of the Picture property to Form1
' picture box.
objX.Picture = picture2.Picture
End Sub

To use the example, run the application, and click Form1. You'll see the icon
from Form2 appear in the picture box on Form1.

Project for creating an account class:


1. Create a new Standard EXE project.
2. Choose Add class Module from the Project Menu.
3. Rename the m\class module name as caccount.
4. Look in the object browser to find this new class
Adding Properties to the object:
1. Add two private variables in the general declaration section of the class
module. These will be the private storage for two properties: accountid and
balance.
2. Add the property procedures to access these two properties as shown in the
figure 1.
Private msaccountid As String
Private mcbalance As Currency
Public Property Get balance() As Currency
balance = mcbalance
End Property
Public Property Let balance(newbalance As Currency)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


mcbalance = newbalance
End Property
Public Property Get accountid() As String
accountid = msaccountid
End Property
Public Property Let accountid(newid As String)
If Left$(newid, 3) = "CHQ" Then
msaccountid = newid
End If
End Property

Figure 1

Adding Methods to the Object:


Add a new subroutine to the class module. This sub must be publicly available
and named deposit. Add code to the new method to increase the balance by a
given amount.
Add a new function to the class module. This function should be publicly
available and named withdraw. Add code to the new method to decrease the
balance by a given amount.
The two methods are shown in the figure 1a.

Public Sub deposit(amount As Currency)


If amount > 0 Then
balance = balance + amount
End If
End Sub

Public Function withdraw(amount As Currency) As Currency


If amount > 0 Then
If amount > balance Then
amount = balance
End If
balance = balance - amount

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


withdraw = amount
End If
End Function
Figure 1a

Creating a client to the Object:


Add a form to the object. Add three labels, a textbox and two commandbuttons
and caption them as shown below.
Object Caption Name
Form Bank Account frmaccount
Label1 Current Balance lblcurbl
Label2 blank lblbalance
Label3 amount txtamount
TextBox n/a txtamount
Commdbutton1 deposit cmddeposit
Commandbutton2 withdrawl cmdwithdraw

Enter the code as shown in the figure 1b for the form objects.
Private acct As caccount
Private Sub Form_Load()
Dim stemp As String
Do
stemp = InputBox("what is the account id?")
Loop Until Len(stemp)
Set acct = New caccount
acct.accountid = stemp
Caption = "account# " & acct.accountid
updatebalance
End Sub

Private Sub updatebalance()


lblbalance.Caption = Format$(acct.balance, "currency")
End Sub

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Private Sub cmddeposit_click()
acct.deposit txtamount.Text
updatebalance
End Sub

Private Sub cmdwithdraw_click()


Dim amt As Currency
amt = acct.withdraw(txtamount.Text)
updatebalance
MsgBox "withdrawl " & Format$(amt, "currency")
End Sub
Figure 1b

Save the Project and run the program. Enter an amount in the textt box. Click
deposit. Balance increases. Enter an amount in the text box. Balance
decreases. The output window looks as in the figure 2.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2

Object Browser:

One can create any number of classes in a VB project. Each class can have
any number of properties and methods. In order to view the classes, the
properties and methods you use the object browser. To open the Object
Browser window click the item object browser from the view menu. A typical
object browser window for the above project, where we have created a class
called caccount will look as sgown in the figure 2a.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 2a

The object browser has four main parts. The bottom of the window is
dominated by two lists. The one on the left is a list of all the objects currently
available to the IDE. Scrolling through this list , many common objects can be
seen, such as Forms, Printers, Command buttons etc. Selecting an object from
this list changes the contents of the right list box. The rightside listbox displays
the properties, methods and events of the selected object. Selecting a property,
method or event from the right listbox displays the syntax and a brief
description in the bottom area of the object. This will help in locating and
identifying the current object, property, method or event to use in a situation.
After the desired procedure has been found, the command can be copied to the
clipboard for pasting into a code window.

Project using class module for computing salary:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Create an employee class and enter the code in the class module as shown in the
figure 3. Open a form window and draw 8 labels, 3 buttons and 8 text boxes,
caption them, size them and position them. Enter the code as shown in the figure 3a.
The output window looks as in the figure 4.

Option Explicit

Dim theEmployee As CEmployee

Private Sub cmdCreate_Click()

Set theEmployee = New CEmployee


With theEmployee
.FirstName = txtFirst.Text
.LastName = txtLast.Text

If IsNumeric(txtSalary.Text) Then
.Salary = txtSalary.Text
Else
MsgBox "Please enter a number"
txtSalary.SetFocus
Exit Sub
End If

If IsNumeric(txtHours.Text) Then
.Hours = txtHours.Text
Else
MsgBox "Please enter a number"
txtHours.SetFocus
Exit Sub
End If

If IsDate(txtHireDate.Text) Then
.HireDate = txtHireDate.Text
Else
MsgBox "Please enter a date"
txtHireDate.SetFocus
Exit Sub
End If

lblFullName.Caption = .FullName
lblYearsOfService.Caption = .YearsOfService
lblWage.Caption = Format$(.Wage, "Currency")

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


End With

End Sub

Private Sub cmdEnd_Click()


Unload Me
End Sub

Private Sub cmdRaise_Click()


Dim Raise As Single
Dim Msg As String

Msg = "How much of a raise (in percent)?"


Raise = CSng(InputBox$(Msg, "Employee Raise", 5))

If Not theEmployee Is Nothing Then


theEmployee.AddRaise Raise
MsgBox "Employee given a raise"
txtSalary.Text = Format$(theEmployee.Salary, "Currency")
cmdCreate_Click
End If

End Sub

Figure 3

Option Explicit

Dim theEmployee As CEmployee

Private Sub cmdCreate_Click()

Set theEmployee = New CEmployee


With theEmployee
.FirstName = txtFirst.Text
.LastName = txtLast.Text

If IsNumeric(txtSalary.Text) Then
.Salary = txtSalary.Text
Else
MsgBox "Please enter a number"
txtSalary.SetFocus
Exit Sub
End If

If IsNumeric(txtHours.Text) Then

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


.Hours = txtHours.Text
Else
MsgBox "Please enter a number"
txtHours.SetFocus
Exit Sub
End If

If IsDate(txtHireDate.Text) Then
.HireDate = txtHireDate.Text
Else
MsgBox "Please enter a date"
txtHireDate.SetFocus
Exit Sub
End If

lblFullName.Caption = .FullName
lblYearsOfService.Caption = .YearsOfService
lblWage.Caption = Format$(.Wage, "Currency")

End With
End Sub

Private Sub cmdEnd_Click()


Unload Me
End Sub

Private Sub cmdRaise_Click()


Dim Raise As Single
Dim Msg As String

Msg = "How much of a raise (in percent)?"


Raise = CSng(InputBox$(Msg, "Employee Raise", 5))

If Not theEmployee Is Nothing Then


theEmployee.AddRaise Raise
MsgBox "Employee given a raise"
txtSalary.Text = Format$(theEmployee.Salary, "Currency")
cmdCreate_Click
End If
End Sub

Figure 3a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 4

x-----------------------------------------------------x

Visual Basic-6
20. DataBases and Data Access Objects

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Two Methods of Interfacing with the jet Database Engine:

Visual Basic provides two methods of interfacing with the Jet database engine: the
Data control and data access objects. While the Data control gives you limited
ability to access existing databases without programming, the DAO model is a
complete programming interface that gives you total control of the database. These
two methods are not mutually exclusive; in fact, there are many situations where you
will want to use both of them together.
The DAO model is a collection of object classes that model the structure of a
relational database system. They provide properties and methods that allow you
to accomplish all of the operations necessary to manage such a system, including
facilities for creating databases, defining tables, fields and indexes, establishing
relations between tables, navigating and querying the database, and so on.
The Jet database engine translates these operations on data access objects
into physical operations on the database files themselves, handling all the
mechanics of interfacing with the different supported databases.
Database programming in Visual Basic consists of creating data access
objects, such as Database, TableDef, Field, and Index objects, that correspond to
the various parts of the physical database you want to access. You use the
properties and methods of these objects to perform operations on the database.
You can display the results of these operations and accept input from the user on
Visual Basic forms, using both bound and unbound controls.
This approach simplifies the code you need to write and insulates you from
the underlying structure and mechanics of retrieving and updating data. It gives
you great flexibility, because you can use the same objects, properties, and
methods to work with a wide variety of supported database formats. Also, if you
change from one database format to another (for example, porting a local
Microsoft Access database to a SQL Server database on a network), you'll need
to make few changes in your code to accommodate the change. You can even
create applications that join tables from two or more different databases in a
single query or report.
There are three categories of databases that Visual Basic recognizes through
DAO and the Jet engine:

Visual Basic Databases

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Also called native databases, these database files use the same format as
Microsoft Access. These databases are created and manipulated directly by
the Jet engine and provide maximum flexibility and speed.
• External Databases

These are Indexed Sequential Access Method (ISAM) databases in several


popular formats, including Btrieve, dBASE III, dBASE IV, Microsoft FoxPro
versions 2.0 and 2.5, and Paradox versions 3.x and 4.0. You can create or
manipulate all of these database formats in Visual Basic. You can also access
text file databases and Microsoft Excel or Lotus 1-2-3 worksheets.

ODBC Databases

These include client-server databases that conform to the ODBC standard,


such as Microsoft SQL Server. To create true client-server applications in
Visual Basic, you can use ODBCDirect to pass commands directly to the
external server for processing.

Note There are other methods of data access supported by Visual Basic, which
do not use the Jet database engine. The ODBCDirect mode of Data Access
Objects allows you to access ODBC data directly, using the same object model
and syntax but bypassing the Jet engine. In addition, the Remote Data Objects
(RDO) library and Remote Data control (RDC) are included in the Enterprise
Edition, and allow direct access to ODBC data. Finally, there are the ODBC
Libraries, which allow you to call the ODBC applications programming
interface (API) directly, and the Visual Basic SQL Libraries (VBSQL), which
provides a direct link to the Microsoft SQL Server API. The toolkits for these
libraries are available as separate Microsoft products.

The data access object model is the Jet database engine's object-oriented
interface. It is a hierarchy of classes that correspond to a logical view of a
relational database system, such as the database itself, the tables defined in it
and their fields, indexes, and so on. These classes are used to create data access
objects that refer to the particular database you want to manipulate.
For consistency and ease of use, these classes and the objects created from
them behave like other classes and objects in the Visual Basic environment. They
are addressed using the familiar Visual Basic syntax and manipulated through
their properties and methods.
The data access object classes are organized as a hierarchy, in which most
classes belong to a collection class, which in turn belongs to another class above
it in the hierarchy. The entire DAO hierarchy is illustrated here.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Dengine
|
Workspace
|
Dastabase
|
TableDef QueryDef Recordset Container Relation
|
Field
|
I index
|
Field

Classes, Objects, and Collections


The notion of an object hierarchy simply means that objects can contain
other objects, which can in turn contain other objects. This "containment" is
accomplished through a special kind of object called a collection. The sole
purpose of a collection object is to contain other objects. The objects contained
by a given collection are all of the same kind.
Note The elements in the DAO hierarchy are actually classes, not objects. They
are the "blueprints" for the objects that you create to build your database
application. A class is similar to a data type, in that it describes what "kind" of
object you are referring to. For example, when you declare

Dim MyWs As Workspace

you are stating that MyWs is a variable that stands for an object of the
Workspace class.

Since most of the discussion in this chapter concerns the behavior of the
objects you create, the term "object" is used in preference to "class." Just
remember that the term "Database object," for example, means "an object of
the Database class."
As the illustration shows, most of the data access objects are represented as
both "object and collection." At the top of the hierarchy is the Microsoft Jet
database engine itself, the DBEngine object. It is the only data access object that
is not contained in anything. It owns a collection called Workspaces (the name of
a collection is always the plural of the objects it contains), which contains one or
more Workspace objects. Each Workspace object has a Databases collection,
which contains one or more Database objects. Each Database object has a
TableDefs collection, which contains one or more TableDef objects, and so on.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Collection Syntax
The member objects of a collection can be accessed through a zero-based
index. For example, the first TableDef in a Database called MyDatabase is
referred to as MyDatabase.TableDefs(0). The second TableDef in the same
Database is MyDatabase.TableDefs(1), and so on.
Objects in the hierarchy are identified by the full "path" through the nested
collections to which they belong, using the . (dot) navigation operator. Thus,
DBEngine.Workspaces(0).Databases(0).TableDefs(0).Fields("Customer")

refers to the field named Customer in the first TableDef in the TableDefs
collection of the first Database in the Databases collection of the first Workspace
in the Workspaces collection of the DBEngine. Some collections also permit
other indexes. As shown in the preceding example, the Fields collection also
enables you to index using a string, corresponding to the Field object's Name
property.
When you refer to a collection member explicitly (as opposed to using an index
to the collection), use the ! (bang) operator instead of the dot. Thus, the following
expressions are equivalent:

MyTableDef.Fields("Customer")
MyTableDef.Fields!Customer

Default Collections
Most data access objects have default collections. These enable you to simplify
your code, because you do not have to explicitly provide the collection name
when referring to an element from the default collection. For example, the
default collection of the Recordset object is the Fields collection. To get the value
of a Field named Customer, you can simply write:
Cust = MyRecordset!Customer ' Gets value of "Customer" field.

which is shorter than


Cust = MyRecordset.Fields!Customer

– Or –
Cust$ = Myrecordset.Fields("Customer")

Default collections simplify your code when making nested object references,
because the default collections are the ones that implement the main hierarchy of
data access objects.

Properties and Methods:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


One of the main ideas of object oriented programming is that all of the data and
procedures related to a particular object are kept together with the object itself. In
Visual Basic, an object's data (settings or attributes) are called properties, while the
various procedures that can operate on the object are called its methods.
Programming with data access objects consists of creating object variables,
and manipulating them by invoking their methods and setting their properties.
For example, consider the following code fragment:
Dim MyDB As Database, MyWS As Workspace, _
MyRS As Recordset

Set MyWS = DBEngine.Workspaces(0)


Set MyDB = MyWS.OpenDatabase("Accounts.mdb")
Set MyRS = MyDB.OpenRecordSet("Clients")

MyRS.Index = "ClientID"

1. The OpenDatabase method of the MyWS Workspace object is used to open


the Accounts.mdb database, and assign it to the MyDB Database object
variable.

2. Next, MyDB's OpenRecordset method is used to create a recordset (a


group of records representing a database table or the results of a query) based on
the Clients table, and assign it to the MyRS Recordset variable.

3. Finally, the Index property of the MyRS Recordset object is set to the
ClientID Index.

Other methods of the Recordset object could be used to navigate through the
records, add a new record to the table, edit a record or delete a record. Other
properties could be examined or set to filter the Recordset, determine when it
was last updated, and change other attributes of the Recordset.
Writing a value into a property may cause the object to take a specific action.
In the preceding example, setting the Recordset object's Index property causes
the logical sort order of the Recordset to instantly change to match the specified
index.
The user can define new properties on most data access objects. This is a
powerful programming tool that enables you to customize objects and save the
changes permanently with the object in the database.

Now that you have been introduced to the basic concepts of database
programming with data access objects and the Jet engine, the next step is to see

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


how the various pieces fit together to create database applications. There are two
broad areas into which all database programming tasks can be categorized. The
common terms for these areas are:
Data Definition Language (DDL)
Data Manipulation Language (DML)

This doesn't mean that there are two separate languages involved. It is simply a
way of grouping the language elements — in this case, data access objects,
properties, and methods — that are used to define the structure of a database,
and those that are used to manipulate it.

Data Definition
DDL consists of those properties and methods that are used to define and create
the database itself, including its tables, fields, relations, and so on. In traditional
database terminology, this set of definitions constitutes the database's schema.
Defining the database is typically a one-time operation, because the Jet engine
stores the data access objects that define the database schema in the database
itself. Once the database has been created, there is no need to specify its
structure in order to access it. Simply opening the database brings all of its
objects, including those that define its structure, under the management of the
DAO interface.

Data Manipulation
DML consists of the properties and methods that you use to write applications
that access and manipulate existing databases. This includes facilities for
querying the database, navigating through its tables, performing updates, and
adding or deleting records.
If you are working exclusively with databases that have already been created by
another application, it is possible to create applications entirely within the DML
functionality. Understanding the DDL methods, however, will add to your
knowledge of database structure and make you a more flexible database
programmer
There are many ways of organizing databases. Among the most popular are
indexed sequential access method (ISAM) file systems, network-model
databases, hierarchical databases, and relational databases. These types of
databases differ not only in the way they physically manage the storage and
retrieval of data, but also in the conceptual models they present to the user and
programmer.
In recent years, the relational model has generally become the de facto standard
for database design. This is due both to the power of the relational model itself,
and because it provides a standard interface called Structured Query Language
(SQL) that allows many different database tools and products to work together

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


in a consistent and understandable way. The Microsoft Jet database engine is a
relational database engine.
The relational database model presents the data as a collection of tables. Instead
of modeling the relationships in the data according to the way that it is
physically stored, the structure is defined by establishing relations between
simple tables.

Tables, Fields, and Records


Regardless of how it's physically stored in the database file, a table can be
viewed as a set of rows and columns, similar to the rows and columns of a
spreadsheet. In a relational database, the rows are called records and the
columns are called fields. For example, a table of customers might look like:
Customer Table
CustID LastName FirstName Address City ST Zip
1723 doe john xxxx ny ny 10043
3391 smith mary yyyy boston ma 60781
8765 blasé mortimer zzzz peori il 20115

Each row in the table is a record that contains all of the information about a
particular customer, and each record contains the same types and number of
fields: CustID, LastName, FirstName, and so on.

Keys
A key is a field or fields in the table that is indexed for fast retrieval. A key can
be unique or non-unique, depending on whether duplicates are allowed. A
unique key can be designated as the primary key, designating it as the unique
identifier for each row of the table. In the preceding example, for instance, the
customer identification number (CustID) is the table's primary key, because the
CustID uniquely identifies one and only one customer.

Relations
A database can be composed of more than one table, and the tables can be
related to one another in various ways. For example, the customer database
might also have a table listing all of the orders placed by a particular customer.
Rather than repeating all of the customer information for each entry in the
orders table, it could contain a single field that referred to the customer who
placed the order, as shown in the following table.
Order Table
Order CustId Date Item Amount
14764 3391 2/23/94 27 22.95

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


14932 3391 3/17/94 46 9.57
15168 8765 2/15/94 27 22.95

In this table, the CustID field refers to the CustID field in the customer table,
relating the order to the customer who placed it. We can see that customer 3391
(Mary Smith) ordered Item 27 on 2/23/94 and Item 46 on 3/17/94. The key that
establishes the relation is called a foreign key, because it relates to the primary
key of a "foreign" table (the Customers table).

One-to-Many and Many-to-Many


The type of relation shown in the preceding table is called a one-to-many
relation, because one customer can place many orders, but a particular order is
placed by one and only one customer. It is also possible to establish relations that
are many-to-many. For example, there may be an inventory table that lists all of
the items available for sale, as follows.

Inventory Table

Item description supplier cost inventory


27 strawhat gardensup 14 50
46 gardenglo gardensup 4.5 35
102 habgplate floralind 6 137

Here we can see that there is a many-to-many relationship between customers


and inventory items. That is, one customer can order many inventory items, and
one inventory item can be ordered by many different customers. A many-to-
many relationship is defined by creating two separate one-to-many relationships,
with the common "many" table containing foreign keys to both of the other
tables. In this example, the Orders table is related to both the Inventory table
(through Item) and the Customer table (though CustID). By looking at all three
tables, we can see that Mary Smith (CustID 3391) ordered both a straw hat
(Item 27) and garden gloves (Item 46), and that straw hats (Item 27) were
ordered by both Mary Smith (CustID 3391) and Mortimer Blaselflatz (CustID
8765). This relationship is clearer if we create a "junction" table by joining the
relevant fields from the Customer and Inventory tables to the Order field from
the Orders table

Junction table
Order# custid lastname firstname item description
14764 3391 smith mary 27 strawhat

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


14932 3391 smith mary 46 gardengloves
15168 8765 blas mortimer 27 strawhat

Normalization
The task of the database designer is to structure the data in a way that
eliminates unnecessary duplication and provides a rapid search path to all
necessary information. The process of dividing the information into separate
tables that meet these goals is called normalization.
Normalization can be a complex process with many specific rules and different
levels of normal form. For a complete discussion of the process one must refer to
advanced books. However, normalizing most simple databases can be
accomplished by following a simple rule of thumb: tables that contain repeated
information should be divided into separate tables to eliminate the duplication.
For example, a student database that matches students to courses contains the
information shown in the following table.

Student course course description instructor

1 4 physiology dawson
2 3 basketweaving carmuth
3 1 physics adams
4 4 physiology dawson

If there are 1,000 students taking a dozen courses, each course description and
instructor will appear 100 or more times — once for each student who takes that
course. To avoid this inefficiency, the table should be normalized by dividing it
into two separate tables, one for students and one for courses, as follows.

Student Course
1 4
2 3
3 1
4 4

course course description instructor

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


1 physics adams
2 sociology beckley
3 basketweaving carmuth
4 physiology dawson
Because the tables are normalized, changing the Course Description or
Instructor for a particular course can now be accomplished by changing a
single record.

For a brief example, you can look at the design of the Biblio.mdb sample
database included with Visual Basic version 5.0. This is a bibliography of books
about database programming. The information you will want to track about
each book includes:
Author
Title
Year Published
ISBN (International Scientific Book Number)
Publisher (Short bibliographic name)
Company Name (Publisher's full business name)
Address
City
State
Zip
Telephone
Fax
Publisher's comments

Of course, you could simply create a single table with a field for each of the data
items listed. Looking closely at the data, however, it's obvious that such a table
would contain many redundancies. For example, many authors have written
more than one book, and many publishers have published more than one book
on database programming. If you put all fields into a single table, there would be
many duplicate entries in the Author field and in all of the fields that relate to
the Publisher.
Accordingly, you can break the table into three groups: Titles, Authors, and
Publishers, as shown in the following illustration.
Titles Authors Publishers
Title author name

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Year published company

Isbn address
city
state
zip
telephone
fax

Now you need a means of relating the tables to one another. First, assign
primary keys to each table. The Titles table already has the ISBN as a natural
unique key, and you add Au_ID and PubID as unique keys to the Authors and
Publishers tables, respectively.
Titles Authors Publishers
pub-id
Title au-id name
Year published author company
Isbn address
city
state
zip
telephone
fax

Finally, you add Au_ID and PubID to the Titles table as foreign keys into the
Authors and Publishers tables, respectively.
Titles Authors Publishers

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


pub-id
Title au-id name
Year published author company
Isbn address
Au-id city
Pub-id state
zip
telephone
fax

This schema creates one-to-many relationships between the Authors and Titles
tables (an author may write many titles) and between the Publishers and Titles
tables (a publisher may publish many titles). It also creates a many-to-many
relationship between Authors and Publishers (an author's titles may be
published by many publishers, and a publisher's titles many be written by many
authors).
After the database is designed, the next step is to create it.
DAO isn't the only method of creating a new database. Other possible
approaches include:
The Data Manager application included with Visual Basic. With the Data
Manager, you can create a Jet database without programming. Once the
database is created, you can modify and manipulate it using the methods
discussed later in this chapter and in "Accessing and Navigating Databases."
For information on using the Data Manager application, see Help in the Data
Manager.
Microsoft Access. Because it uses the same database engine and format as
Visual Basic, databases you create with Microsoft Access can be used just as if
you had created them directly in Visual Basic. (The exception to this rule is
that Jet version 3.0 databases created by Access can only be used with Visual
Basic applications that also use the Jet version 3.0 engine.) For more
information about the two versions, see the discussion that follows under "16-
Bit or 32-Bit."
An external database application. Products such as FoxPro, dBASE, or ODBC
client/server applications can create a new external database that Visual Basic
can access through ISAM or ODBC drivers.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Create a new directory. For ISAM databases, simply creating a new directory
in Windows® using File Manager, or by using the MKDIR command in MS-
DOS®, essentially "creates" a new database. You will still need to use the
external database application or data access objects to add tables, records,
and fields. See "Modifying the Database" later in this chapter for more
information.

Despite the many alternatives, this chapter focuses on using the self-contained
tools in Visual Basic to create a new database. DAO gives you the greatest depth
of programming control over a database. It is also the method of choice if you
want your application itself to be able to create a new database at run time.
Note You can also create new databases from within your Visual Basic code
using SQL statements that implement DDL. For more information about SQL
statements, see "Writing SQL Queries."

The Structured Query Language (SQL) is an industry-standard database


language used by the Microsoft Jet database engine. SQL is used to create
QueryDef objects, as the source argument to the OpenRecordset method, and as
the RecordSource property of the data control. It can also be used with the
Execute method to directly create and manipulate Jet databases, and to create
SQL PassThrough queries to manipulate remote client-server databases.
This chapter will address the basic structure of SQL, and the ways it is used for
creating, maintaining, and modifying databases. It will also cover the
construction and use of SQL queries to create Recordset objects, and to select,
sort, filter, and update data in the underlying database tables

SQL is a database programming language with origins closely connected to the


invention of the relational database by E. F. Codd in the early 1970's. An early
forerunner of today's SQL was the Sequel language, and for this reason SQL is
still commonly pronounced like "sequel" rather than "ess cue ell," although
both pronunciations are acceptable.
Modern SQL has evolved into a widely used standard for relational databases,
and is defined by the ANSI standard. Most implementations of SQL have minor
variations from the defined standard, including the version supported by the Jet
database engine. These differences will be addressed later in this chapter, but the
overall structure and functionality of the language is very consistent from
vendor to vendor. If you have used any implementation of SQL, you will have no
difficulty making the transition to the Microsoft Jet version.

SQL vs. Navigation


As described earlier in this manual, the Microsoft Jet database engine provides
two separate methods for accomplishing most database tasks:
A navigational model that is based on moving around in the database records.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


A relational model that is based on the structured query language (SQL).

The navigational model consists of the properties and methods described in


"Creating and Modifying Databases" and "Working with Records and Fields."
The relational model is described in this chapter.
Programmers who are familiar with file-oriented database systems such as
dBASE, FoxPro, and Paradox might feel more comfortable beginning with the
navigational methods discussed in the previous chapters mentioned above. In
most cases, however, the equivalent SQL methods are more efficient, and they
should generally be used where performance considerations are important. In
addition, SQL has the advantage of being an industry-standard database
interface, so a knowledge of SQL commands allows you to access and
manipulate a wide variety of database products from many different vendors.
In practice, you will often find yourself using both models together. For example,
you might use an SQL SELECT statement to create a small recordset of selected
items from a large table, then use the Move navigational methods to step
through the recordset and examine particular records one at a time.
Note The relational terms row and column are equivalent to the more familiar
database terms record and field. Because SQL is a purely relational database
language, the terms row and column are most frequently used to describe the
operation of SQL commands. To avoid confusion, both sets of terms will be used
interchangeably in this chapter. Just remember that a row is a record, and a
column is a field.
The SQL language is composed of commands, clauses, operators, and aggregate
functions. These elements are combined into statements used to create, update,
and manipulate databases. The following sections briefly describe these elements
of the SQL language, and the remainder of this chapter presents specific
examples of their use.
Note The following sections present many of the most commonly used SQL
commands and keywords, but not all of them. For a complete reference listing of
SQL keywords, search for "
Like the DAO navigational methods, SQL provides both data definition
language (DDL) and data manipulation language (DML) commands. Although
there are some areas of overlap, the DDL commands allow you to create and
define new databases, fields, and indexes, while the DML commands let you
build queries to sort, filter, and extract data from the database.

DDL
DDL statements in SQL are expressions built around the following commands.
Command Description

CREATE Used to create new tables, fields, and indexes.


DROP Used to delete tables and indexes from the database.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


ALTER Used to modify tables by adding fields or changing field definitions.
DML
DML statements are expressions built around the following commands.
Command Description

SELECT Used to query the database for records that satisfy specific criteria.
INSERT Used to load batches of data into the database in a single operation.
UPDATE Used to change the values of particular records and fields.
DELETE Used to remove records from a database table.

Clauses are modifying conditions used to define the data you want to select or
manipulate. The following table lists the clauses you can use.
Clause Description

FROM Used to name the table from which records are to be selected.
WHERE Used to specify the condition(s) the records must meet to be selected.
GROUP BY Used to separate the selected records into specific groups.
HAVING Used to state the condition to be satisfied by each group.
ORDER BY Used to sort the selected records according to a specified order.

There are two kinds of operators in SQL: logical operators and comparison
operators.

Logical Operators
Logical operators are used to connect expressions, usually within a WHERE
clause. For example:
SELECT * from Mytable WHERE condition1 AND condition2

Here the AND operator connects the expressions condition1 and condition2, to
specify that both conditions must be met to satisfy the selection criteria. The
logical operators include:
AND
OR
NOT

Comparison Operators
Comparison operators are used to compare the relative value of two expressions
to determine what action should be taken. For example:
SELECT * from Publishers WHERE PubId = 5

Here the '=' operator specifies that only those records that have a PubID field
with a value of 5 will be selected.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The comparison operators are listed in the following table.
Operator Meaning/Usage

< Less than


<= Less than or equal to
> Greater than
>= Greater than or equal to
= Equal to
<> Not equal to
BETWEEN Used to specify a range of values
LIKE Used in pattern matching
IN Used to specify records in a d

Aggregate functions are used within a SELECT clause on groups of records to


return a single value that applies to a group of records. For example, the AVG
aggregate function can return the average of all the values in a particular field of
a recordset. The following table lists the aggregate functions.
Aggregate function Description

AVG Used to obtain the average of the values in a particular field.


COUNT Used to return the number of records in the selection.
SUM Used to return the sum of all the values in a particular field.
MAX Used to return the highest value in a specified field.
MIN Used to return the smallest value in

The SQL data definition language (DDL) includes a number of commands you
can use to create tables and indexes, and modify tables by adding or removing
columns or indexes. These data definition statements can only be used with Jet
databases; they are not supported for any of the external database formats.
Note To use the DDL commands, or any query that doesn't return rows of
records, enclose the entire statement in double quotes and use it as the argument
to the Execute method of a Database or QueryDef object, as in:

MyDB.Execute "CREATE TABLE Employees _


([First Name] TEXT, [Last Name] TEXT)"

To use any of the commands that return rows (such as SELECT), use the
statement as the source argument to the OpenRecordset method, as in:
MyDB.OpenRecordset("SELECT * FROM Titles WHERE _
Au_ID = 5",dbOpenDynaset)

To create new tables in a database, use the CREATE TABLE statement. The
complete statement accepts arguments for the table name and, for each column
(field), you add a set of arguments for the field name, data type, and, for text
columns, size in characters.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The following example creates a table called "Employees," having two text
columns of 25 characters each:
CREATE TABLE Employees ([First Name] TEXT (25), _
[Last Name] TEXT (25))

Adding and Removing Columns


You can add, modify, or remove columns in a table with the ALTER TABLE
statement. For example, the following statement adds a 25-character Text
column named "Notes" to the Employees table:
ALTER TABLE Employees ADD COLUMN Notes TEXT(25)

To remove a column, use the DROP keyword. This example removes the
"Notes" column added in the previous example:
ALTER TABLE Employees DROP COLUMN Notes

To modify a column, you must first delete it, and then add a new column of the
same name. The following example increases the size of the Notes column by
dropping it from the table, and then adding a new, longer Notes field:
ALTER TABLE Employees DROP COLUMN Notes;
ALTER TABLE Employees ADD COLUMN Notes TEXT(30);

Note Using ALTER TABLE, you can add or delete only one column at a time.

There are three different ways to create an index:


At table creation, with the CREATE TABLE statement.
With the CREATE INDEX statement.
With the ALTER TABLE statement.

Although all three approaches can be used to create similar indexes, there are
some differences. If you want to add a foreign key and enforce referential
integrity, you must use a CONSTRAINT clause in a CREATE TABLE or
ALTER TABLE statement.
Sometimes it is preferable to create a table without an index first, and then
design the index parameters after using the prototype table. In this situation,
you would use CREATE TABLE to create the prototype table with no index,
and then later on add the index with CREATE INDEX or ALTER TABLE.

Creating an Index with CREATE TABLE


When you create a table, you can create an index on individual columns, or
across two or more columns, using the SQL CONSTRAINT clause (the
CONSTRAINT keyword begins the definition of an index). The following
example shows how to create a table with a 3-column index:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


CREATE TABLE Employees ([First Name] TEXT (25), _
[Last Name] TEXT (25), [Date of Birth] DATETIME, _
CONSTRAINT EmployeesIndex UNIQUE _
([First Name], [Last Name], [Date of Birth]));

To index only one column, you put the CONSTRAINT clause in one of the
column definitions. For example, to index the Date of Birth column only, you
would use the following CREATE TABLE statement:
CREATE TABLE Employees ([First Name] TEXT (25), _
[Last Name] TEXT (25), [Date of Birth] DATETIME _
CONSTRAINT EmployeesIndex PRIMARY);

The difference between a multiple-column index and a single-column index is


that, for a single-column index, the CONSTRAINT keyword that begins the
index definition is not separated from the last column by a comma, but is instead
immediately after the data type of the indexed column.

Creating an Index with CREATE INDEX


You can also use the CREATE INDEX statement to add an index. This example
yields the same results as the previous example, except it uses CREATE INDEX
instead of ALTER TABLE:
CREATE UNIQUE INDEX MyIndex ON Employees _
([Date of Birth])

In the optional WITH clause, you can enforce data validation rules: PRIMARY,
meaning this is the primary index column; DISALLOW NULL, meaning this
column may not be left blank; or IGNORE NULL, meaning that the record will
not be indexed if this column is blank.
The following example adds a WITH clause to the previous example, so that no
record may be added to the table with an empty social security number column:
CREATE UNIQUE INDEX MyIndex ON Employees (SSN) _
WITH DISALLOW NULL

Note Don't use the PRIMARY keyword when you create a new index on a table
that already has a primary key; if you do, an error occurs.

You can use CREATE INDEX to create an index specification on an attached


table that does not already have an index. To create such an index, you don't
need permission or access to the remote server, and the remote database is
unaware of and unaffected by the index. You use the same syntax for attached
and native tables. This can be especially useful to create an index on a table that
would ordinarily be read-only because it lacks an index.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Creating an Index with ALTER TABLE
You can also add an index to an existing table using the ALTER TABLE
statement, using the ADD CONSTRAINT syntax. For example, this statement
adds an index to the "SSN" column of a table:
ALTER TABLE Employees ADD CONSTRAINT MyIndex _
PRIMARY (SSN)

You can also add a multiple-column index to a table using the ALTER TABLE
statement, like this:
ALTER TABLE Employees ADD CONSTRAINT NameIndex _
UNIQUE ([Last Name], [First Name], SSN)

The CONSTRAINT Clause and Referential Integrity


A constraint is an index. You use the CONSTRAINT clause to create or delete
indexes with the CREATE TABLE and ALTER TABLE statements, as shown in
the preceding section.
The CONSTRAINT clause also allows you to define primary and foreign keys, to
define relations and enforce referential integrity.
For More Information For information about relations and referential
integrity, see "Creating and Modifying Databases."

There are two types of CONSTRAINT clauses: one for creating an index on a
single field and one for creating an index on more than one field.
The syntax for the single-field index is:
CONSTRAINT name {PRIMARY KEY | UNIQUE | REFERENCES
foreigntable [(foreignfield1, foreignfield2)]}

The syntax for a multiple-field index is:


CONSTRAINT name {PRIMARY KEY (primary1[, primary2 [, ...]])
|UNIQUE (unique1[, unique2 [, ...]]) |FOREIGN KEY (ref1[, ref2 [, ...]])
REFERENCES foreigntable [(foreignfield1 [, foreignfield2 [, ...]])]}

The following arguments apply to both versions.


Argument Description

name The name of the index to be created.


primary1, primary2 The name of the field or fields to be designated the primary
key.
unique1, unique2 The name of the field or fields to be designated as a unique
key.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


ref1, ref2 The name of a foreign key field or fields that refer to fields in another
table.
foreigntable The name of the foreign table containing the field or fields specified
by foreignfield.
foreignfield1, foreignfield2 The name of the field or fields in foreigntable specified
by ref1, ref2.

Using CONSTRAINT, you can designate a field as one of the following types of
indexes:
UNIQUE — designates a field as a unique key. This means that no two
records in the table can have the same value in this field. You can constrain
any field or list of fields as unique. If a multiple-field index is designated as a
unique key, the combined values of all fields in the index must be unique, even
if two or more records have the same value in just one of the fields.
PRIMARY KEY — designates one field or set of fields in a table as a primary
key. All values in the primary key must be unique, and there can be only one
primary key for a table. If you set a PRIMARY KEY constraint on a table
that already has a primary key, an error occurs.
FOREIGN KEY — designates a field as a foreign key. If the foreign table's
primary key consists of more than one field, you must use a multiple-field
index definition, listing all of the referencing fields, the name of the foreign
table, and the names of the referenced fields in the foreign table in the same
order that the referencing fields are listed. If the referenced field or fields are
the foreign table's primary key, you don't have to specify the referenced fields
by defaultthe Jet engine behaves as if the foreign table's primary key is the
referenced fields.

For example, to add the PubID index for the Titles table of the Biblio.mdb
sample database, you could use the following statement:
ALTER TABLE Titles ADD CONSTRAINT MyIndex _
FOREIGN KEY (PubID) REFERENCES Publishers (PubID}

Notice that by using the FOREIGN KEY keywords, you are creating a relation
between the PubID field of the Titles table (foreign key) and the PubID field of
the Publishers table (primary key). This relation will be enforced by the Jet
engine, just as if you had used the CreateRelation method described in
"Creating and Modifying Databases."

The SQL data manipulation language (DML) statements are used to retrieve
records in tables, update records, and add or delete records in tables. A number
of different statements are supported for these tasks, but most of them fall
within the general structure of the SELECT query.

The Select Query

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Use the SELECT statement to retrieve records from the database as a set of
records, storing them in a new Recordset object. Your application can then
manipulate this recordset — displaying, adding, changing, and/or deleting
records as needed. Your application can also display and produce reports from
the data.
SELECT is usually the first word in an SQL statement. Most SQL statements
are either SELECT or SELECT...INTO statements. You can use a SELECT
statement in the SQL property of a QueryDef object, in the RecordSource
property of a data control, or as an argument for the OpenRecordset method.
SELECT statements don't change data in the database; they only retrieve data.
The overall form of the SELECT query is as follows:
SELECT fieldlist
FROM tablenames IN databasename
WHERE searchconditions
GROUP BY fieldlist
HAVING group criteria
ORDER BY fieldlist
WITH OWNERACCESS OPTION

Each of these statements and clauses will be discussed in the following sections.

The Basic Query


The simplest possible SELECT query is
SELECT * FROM tablename

For example, the following SELECT query will return all columns of all records
in the Employees table:
SELECT * FROM Employees

The asterisk indicates that all columns of the desired table(s) are to be retrieved.
You could specify only certain columns. When displayed, data for each column
will appear in the order in which they are listed, so you can re-order columns for
readability:
SELECT [First Name], [Last Name] FROM Employees

Specifying the Data Source


A SELECT statement will always have a FROM clause, indicating the table or
tables from which records will be drawn.
If a field name is included in more than one table in the FROM clause, precede it
with the table name and the . (dot) operator. In the following example, the
Department field is in both the Employees table and the Supervisors table. The

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


SQL statement selects Department from the Employees table and SupvName
from the Supervisors table:
SELECT Employees.Department, SupvName _
FROM Supervisors, Employees _
WHERE Employees.Department = Supervisors.Department;

When the FROM clause lists more than one table, the order in which they
appear is not important.

Specifying a Table in an External Database


Sometimes, you will need to reference a table in an external database to which
the Microsoft Jet database engine can connect, such as a dBASE or Paradox
database or an external Jet database. You can do this with the optional IN
clause. The IN clause usually appears following a table name in a FROM clause,
but can also be used in a SELECT INTO or INSERT INTO clause, where the
target table is in an external database.
Note You can use IN to connect to only one external database at a time.

In some cases, the path argument refers to the directory containing the database
files. For example, when working with dBASE, FoxPro, or Paradox database
tables, the path argument specifies the directory containing .DBF or .DB files.
The table filename is derived from the destination or tableexpression arguments.
To specify a non-Jet database, append a semicolon (;) to the name, and enclose it
in single (' ') or double (" ") quotation marks. For example:
'dBASE IV;'

You can also use the DATABASE keyword to specify the external database. For
example, both of the following lines specify the same table:
SELECT * FROM Table IN "" [dBASE IV; _
DATABASE=C:\DBASE\DATA\SALES;];
SELECT * FROM Table IN "C:\DBASE\DATA\SALES" _
"dBASE IV;"

Note For improved performance and ease of use, it is almost always better to
use an attached table instead of an IN clause.

For More Information For more information about attached tables, see
"Working with Records and Fields" and "Accessing External Data."

Aliasing the Column Names


When a Recordset object is created from a SELECT statement, the table's
column names become the Field object names in the Recordset. If you want

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


different column names, use the AS clause. The following example uses the title
"DOB" to name the returned Birth Date column from the Employees table:
SELECT [Birth Date] AS DOB FROM Employees;

Whenever you use queries that return ambiguous or duplicate Field object
names, you must use the AS clause to provide an alternate name for the Field.
The following example uses the title "Head Count" to name the returned Field
in the resulting Recordset:
SELECT COUNT(Employee ID) AS [Head Count] _
FROM Employees;

Using Visual Basic Variables in an SQL Statement


In a Visual Basic program, you can create a SELECT statement in your
application by concatenating local variables into the statement as needed to
select, sort, or filter the data as dictated by your application. For example, if you
have a TextBox control (TitleWanted) containing the name of a Title and you
want to fetch all books from the Titles table with this title, you can create an
SQL statement that includes the current value of the TextBox. Note that the
SQL query encloses the TitleWanted value in single quotation marks (' '):
Set Rst = Db.OpenRecordset("SELECT * FROM Titles " _
& " WHERE Title = '" & TitleWanted.T

The procedure for creating a new Jet database is simply a process of creating
and defining data access objects that correspond to the tables, fields, indexes,
and relations of your database design. In this overview, the process will be
presented step-by-step, followed by a complete code example for creating the
Biblio.mdb database. For a complete discussion of the syntax and options for
each method discussed, see the Language Reference in Books Online.
The first step in creating a new database is to create the Database object itself,
and to define its structure by adding TableDef and Field objects that correspond
to your design.
To create a new database
1 Use the Dim statement to create new object variables for each object in your
database. In addition to the DBEngine and default Workspace objects that
make up the working environment, you will need:
One Database object
One TableDef object for each table
One Field object for each field in each table
One Index object for each index in each table

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


For example, to create object variables for the Biblio.mdb database, you could
use the following code:
Dim MyDB As Database, MyWs As Workspace
Dim AuTd As TableDef, TitTd As TableDef, _
PubTd As tableDef
Dim AuFlds(2) As Field, TitFlds(5) _
As Field, PubFlds(10) As Field
Dim AuIdx As Index, TitIdx(3) As Index, _
PubIdx As Index

2 Use the CreateDatabase method of the Workspace object to create the new
database. In this example, the method uses the minimum two arguments: one
to specify the database name, and one to specify the locale:
Set MyWs = DBEngine.Workspaces(0)
Set MyDb = MyWs.CreateDatabase("C:\VB\Biblio.mdb", _
dbLangGeneral, dbVersion30)

Note that the constant dbVersion30 specifies a Jet version 3.0 database. If you
use the dbVersion30 constant to create a version 3.0 database, only 32-bit
applications using the Jet version 3.0 engine or higher will be able to access it.
3 Use the CreateTableDef method of the Database object to create new
TableDef objects for each table in the database, as follows:
Set TitTd = MyDB.CreateTableDef("Titles")
Set AuTd = MyDB.CreateTableDef("Authors")
Set PubTd = MyDB.CreateTableDef("Publishers")

4 Use the CreateField method of the TableDef object to create new Field objects
for each field in the table, and to set properties of each field to define the
field's size, data type, and other needed attributes. For example, the following
code creates the Authors table in the Biblio.mdb database:
Set AuFlds(0) = AuTd.CreateField("Au_ID", dbLong)
' Make it a counter field.
AuFlds(0).Attributes = dbAutoIncrField
Set AuFlds(1) = MyTd.CreateField("Author", dbText)
AuFlds(1).Size = 50

5 Use the Append method to add each field to its table and each table to the
database, as shown in the following code:
AuTd.Fields.Append AuFlds(0)
AuTd.Fields.Append AuFlds(1)
MyDB.TableDefs.Append AuTd

Note In this example, a different variable is used for each data access object, for
clarity. In practice, you can reuse variables to simplify your code. For example,
you can use the Dim statement to declare a single TableDef variable, use

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


CreateTableDef to assign a new TableDef object to it, and append it to the
Database. Once it is appended, you can use the same TableDef variable to create
and append each new TableDef.

You add indexes to the TableDef by creating them with the CreateIndex method.
In order to specify which fields are to be indexed, you create new Field objects
with the CreateField method of the Index object.
To add an index to a database table
1 Create indexes for each table using the CreateIndex method of the TableDef
object, and set their properties:
Set AuIdx = MyTd.CreateIndex("AuthorID")
AuIdx.Primary = True
AuIdx.Unique = True

2 Create fields for each index object using the CreateField method of the Index
object:
Set NewFld = AuIdx.CreateField("Au_ID")

3 Append the field to the Index and the Index to the TableDef object:
AuIdx.Fields.Append NewFld
MyTd.Indexes.Append AuIdx

Note Fields created with the CreateField method of the Index object aren't
added to the TableDef. Instead, they are added to the Index object, and given the
same Name property as the TableDef field that they are to index. You don't
specify Type and Size properties on fields of the Index object.

Relations and Referential Integrity


Creating TableDefs that implement primary and foreign keys, as described
previously, allows you to relate records in one table to the corresponding records
in another table, according to the common primary/foreign key values. For the
relation to be useful, however, it is vital to maintain referential integrity when
adding or deleting records. Referential integrity simply means that the foreign
key(s) in any referencing table must always refer to a valid record in the
referenced table.
For example, in the Biblio.mdb database, the PubID field of the Titles table is a
foreign key that references the PubID key of the Publishers table. If there is a
record in the Titles table with a PubID entry of, for example, 25, there must
actually be a record in the Publishers table with a PubID of 25. If there isn't,
there is no way to determine which publisher published this particular title and
the database is effectively corrupted. This type of corruption is called a
referential integrity violation.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The Jet database engine provides the Relation object to enforce referential
integrity and to prevent such violations.
To add a relation to a database
1 Create a Relation object using the CreateRelation method of the Database
object and set its Table and ForeignTable properties:
Dim Au_Tit As Relation
Set Au_Tit = MyDb.CreateRelation("Authors_Titles")
Au_Tit.Table = "Authors"
Au_Tit.ForeignTable = "Titles"

2 Create a field to define the common primary/foreign key field in the relation,
using the CreateField method of the Relation object:
Dim TempField As Field
Set TempField = Au_Tit.CreateField("Au_ID")
TempField.ForeignName = "Au_ID"

3 Use the Append method to add the Field object to its Relation and the
Relation to the Database.
Au_Tit.Fields.Append TempField
MyDb.Relations.Append Au_Tit

Setting Additional Properties


The Create methods discussed in these topics allow you to set additional
properties and options for the created objects. You can find a complete reference
to all objects, properties, and methods, along with code examples, in the
Language Reference in Books Online.
If you omit one or more of the optional arguments when you use one of the
Create methods, you can use an assignment statement to set or reset the
corresponding property before you append the new object to a collection. For
example,
Set MyFld = MyTableDef.CreateField("ClientName", _
dbText, 30)

As an example of creating a new database in Visual Basic code, the following


procedure was used to create the Biblio.mdb database.
Sub MakeBiblio ()
Dim MyDB As Database, MyWs As Workspace, _
lxFlds(2) As Field
Dim i As Integer
Dim AuTd As TableDef, TitTd As TableDef, _
PubTd As TableDef
Dim AuFlds(2) As Field, TitFlds(5) As Field, _
PubFlds(10) As Field

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Dim AuIdx As Index, TitIdx(3) As Index, PubIdx As Index

Set MyWs = DBEngine.Workspaces(0)


Set MyDB = MyWs.CreateDatabase("C:\VB\Biblio.mdb", _
dbLangGeneral, dbVersion25)
' Create new TableDef for Authors table.
Set AuTd = MyDB.CreateTableDef("Authors")
' Add fields to MyTableDef.
Set AuFlds(0) = MyTd.CreateField("Au_ID", dbLong)
' Make it a counter field.
AuFlds(0).Attributes = dbAutoincrfield
Set AuFlds(1) = MyTd.CreateField("Author", dbText)
AuFlds(1).Size = 50
AuTd.Fields.Append AuFld(0)
AuTd.Fields.Append AuFld(1)
' Now add an Index.
Set AuIdx = AuTd.CreateIndex("Au_ID")
AuIdx.Primary = True
AuIdx.Unique = True
Set IxFlds(0) = AuIdx.CreateField("Au_ID")
' Append Field to Fields collection of Index object.
AuIdx.Fields.Append IxFlds(0)
' Append Index to Indexes collection.
AuTd.Indexes.Append AuIdx
' Append TableDef to TableDefs collection.
MyDB.TableDefs.Append AuTd

' Create new TableDef for Titles table


Set TitTd = MyDB.CreateTableDef("Titles")
' Create fields for Titles Table
Set TitFlds(0) = TitTd.CreateField("Title", dbText)
TitFlds(0).Size = 100
Set TitFlds(1) = TitTd.CreateField("Year Published", _
dbInteger)
Set TitFlds(2) = TitTd.CreateField("ISBN", dbText)
TitFlds(2).Size = 20
Set TitFlds(3) = TitTd.CreateField("Au_ID", dbLong)
Set TitFlds(4) = TitTd.CreateField("PubID", dbLong)
' Append fields to Titles TableDef.
For i = 0 to 4
TitTd.Fields.Append TitFld(i)
Next i
' Now add indexes.
For i = 0 to 2
Set TitIdx(i) = TitTd.CreateIndex()
Next i

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


TitIdx(0).Name = "ISBN"
TitIdx(0).Primary = True
TitIdx(0).Unique = True
Set IxFld(0) = TitIdx(0). CreateField("ISBN")
TitIdx(1).Name = "Au_ID"
TitIdx(1).Primary = False
TitIdx(1).Unique = False
Set IxFld(1) = TitIdx(1). CreateField("Au_ID")
TitIdx(2).Name = "PubID"
TitIdx(2).Primary = False
TitIdx(2).Unique = False
Set IxFlds(2) = TitIdx(2). CreateField("PubID")
' Append fields to Index object of Titles Table.
For i = 0 to 2
TitIdx(i).Fields.Append IxFld(i)
Next i
' Append Indexes to Titles TableDef
For i = 0 to 2
TitTd.Indexes.Append TitIdx(i)
Next i
' Save TableDef definition by appending it to TableDefs
' collection.
MyDB.TableDefs.Append TitTd

' Create new TableDef for Publishers table.


Set PubTd = MyDB.CreateTableDef("Publishers")
' Add field to PubTd.
Set PubFlds(0) = PubTd.CreateField("PubID", dbLong)
' Make it a counter field.
PubFlds(0).Attributes = dbAutoincrfield
Set PubFlds(1) = PubTd.CreateField("Name", dbText)
PubFlds(1).Size = 50
Set PubFlds(2) = PubTd.CreateField("Company Name", _
dbText)
PubFlds(2).Size = 255
Set PubFlds(3) = MyTd.CreateField("Address", dbText)
PubFlds(3).Size = 50
Set PubFlds(4) = PubTd.CreateField("City", dbText)
PubFlds(4).Size = 20
Set PubFlds(5) = MyTd.CreateField("State", dbText)
PubFlds(5).Size = 10
Set PubFlds(6) = PubTd.CreateField("Zip", dbText)
PubFlds(6).Size = 15
Set PubFlds(7) = PubTd.CreateField("Telephone", dbText)
PubFlds(7).Size = 15
Set PubFlds(8) = PubTd.CreateField("Fax", dbText)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


PubFlds(8).Size = 15
Set PubFlds(9) = MyTd.CreateField("Comments", dbText)
PubFlds(9).Size = 50
' Save Field objects by appending to Fields collection.
For i = 0 to 9
PubTd.Fields.Append PubFld(i)
Next i
' Now add an index.
Set PubIdx = PubTd.CreateIndex("PubID")
PubIdx.Primary = True
PubIdx.Unique = True
Set IxFlds(0) = PubIdx.CreateField("PubID")
PubIdx.Fields.Append IxFlds(0)
PubTd.Indexes.Append PubIdx
' Save TableDef object by appending it to TableDefs
' collection.
MyDB.TableDefs.Append PubTd
MsgBox ("Database Created")
MyDB.Close
End Sub

About ActiveX Data Control Obects(ADO)_

Solutions for Local Data Access


The Issue
You want a simple, consistent application programming interface (API) that enables
applications to gain access to and modify a wide variety of data sources. A data source
may be as simple as a text file, complex as a cluster of heterogeneous databases, or
something yet to be invented. Furthermore, the API should not presume the means of
gaining access to and manipulating the data source.
Although these are your specific requirements, the typical data source is a relational
database that supports the Open Database Connectivity (ODBC) standard and is
manipulated with commands written in Structured Query Language (SQL).

The general solution Microsoft offers to this problem is OLE DB, a set of
Component Object Model (COM) interfaces that provide uniform access to data
stored in diverse information sources. However, the OLE DB application
programming interface is designed to provide optimal functionality in a wide
variety of applications; it does not meet the requirement for simplicity.

You need an API that is a bridge between the application and OLE DB. ActiveX®
Data Objects (ADO) is that bridge.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The Solution
ADO defines a programming model—the sequence of activities necessary to gain
access to and update a data source. The programming model summarizes the entire
functionality of ADO.
The programming model suggests an object model—the set of objects that
correspond to and implement the programming model. Objects possess methods that
perform some operation on data, and properties that either represent some attribute
of the data or control the behavior of some object method.

Associated with objects are events, which are notifications that some operation has
occurred, or is about to occur.

Basic ADO Programming Model


ADO provides the means for you to perform the following sequence of actions:

1. Connect to a data source. Optionally, you can ensure that all changes to the
data source occur either successfully or not at all.

2. Specify a command to gain access to the data source, optionally with variable
parameters, or optionally optimized for performance.

3. Execute the command.

4. If the command causes data to be returned in the form of rows in a table,


store the rows in a cache that you can easily examine, manipulate, or change.

5. If appropriate, update the data source with changes from the cache of rows.

6. Provide a general means to detect errors (usually as a result of making a


connection or executing a command).

Typically, you will employ all these steps in the programming model. However, it's
worth noting that ADO is flexible enough that you can do useful work by executing
just part of the model. For example, you could store data from a file directly into a
cache of rows, then use ADO resources merely to examine the data.

The ADO Programming Model in Detail

The following elements are key parts of the ADO programming model:
• Connection

• Command

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


• Parameter

• Recordset

• Field

• Error

• Property

• Collection

• Event

Connection

Access from your application to a data source is through a connection, the


environment necessary for exchanging data. Your application can gain access to a
data source directly (sometimes called a two-tier system), or indirectly (sometimes
called a three-tier system) through an intermediary like the Microsoft® Internet
Information Server.

The object model embodies the concept of a connection with the Connection object.

A transaction delimits the beginning and end of a series of data access operations
that transpire across a connection. ADO ensures that changes to a data source
resulting from operations in a transaction either all occur successfully, or not at all.
If you cancel the transaction or one of its operations fails, then the ultimate result
will be as if none of the operations in the transaction had occurred. The data source
will be as it was before the transaction began.

The object model does not explicitly embody the concept of a transaction, but
represents it with a set of Connection object methods.

ADO accesses data and services from OLE DB providers. The Connection object is
used to specify a particular provider and any parameters. For example, Remote
Data Service (RDS) can be invoked explicitly or it can be invoked implicitly with the
"MS Remote" provider. (Please see the RDS Tutorial for an example of invoking
RDS via the "MS Remote" provider in step 2.)
Command
A command issued across an established connection manipulates the data source in
some way. Typically the command adds, deletes, or updates data in the data source,
or retrieves data in the form of rows in a table.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


The object model embodies the concept of a command with the Command object.
The existence of a Command object gives ADO the opportunity to optimize the
execution of the command.
Parameter
Often, commands require variable parts, parameters, that can be altered before you
issue the command. For example, you could issue the same data retrieval command
repeatedly, but each time vary your specification of the information to be retrieved.

Parameters are especially useful for executing commands that


behave like functions. In this case you know what the command does, but not
necessarily how it works. For example, you issue a bank transfer command that
debits one account and credits another. You specify the amount of money to be
transferred as a parameter.
The object model embodies the concept of a parameter with the Parameter object.
Recordset

If your command is a query that returns data as rows of information in a table (that
is, it is a row-returning query), then those rows are placed in local storage.
The object model embodies this storage as a Recordset object. However, there is no
object that represents a single row of a Recordset.

The Recordset is the primary means of examining and modifying data in the rows.
The Recordset object allows you to:
• Specify which rows are available for examination.

• Traverse the rows.

• Specify the order in which the rows may be traversed.

• Add, change, or delete rows.

• Update the data source with changed rows.

• Manage the overall state of the Recordset.

Field
A row of a Recordset consists of one or more fields. If you envision the Recordset as
a two-dimensional grid, the fields line up to form columns. Each field (column) has
among its attributes a name, a data type, and a value. It is this value that contains
the actual data from the data source.
The object model embodies a field as a Field object.
In order to modify data in the data source, you modify the value of Field objects in
Recordset rows. Ultimately, changes to a Recordset are propagated to the data

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


source. As an option, the transaction management methods on the Connection
object can guarantee that the changes succeed or fail in unison.
Error
Errors can occur at any time in your application, usually as the result of not being
able to establish a connection, execute a command, or perform an operation on an
object in a suitable state (for example, attempting to use a Recordset object that has
not been initialized).
The object model embodies an error as an Error object.
Any given error produces one or more Error objects. The next error that occurs will
discard the previous set of Error objects.
Property
Each ADO object has a set of unique properties that either describe or control the
behavior of that object.
There are two types of properties: built-in and dynamic. Built-in properties are part
of the ADO object and are always available. Dynamic properties are added to the
ADO object's Properties collection by the underlying data provider, and exist only
while that provider is being used.
The object model embodies a property as a Property object.

Collection

ADO provides collections, a type of object that conveniently contains other objects
of a particular type. The objects in the collection can be retrieved with a collection
method either by name, as a text string, or by ordinal, as an integer number.

ADO provides four types of collections:

• The Connection object has the Errors collection, which contains all Error
objects created in response to a single failure involving the data source.

• The Command object has the Parameters collection, which contains all
Parameter objects that apply to that Command object.

• The Recordset object has the Fields collection, which contains all Field
objects that define the columns of that Recordset object.

• In addition, the Connection, Command, Recordset, and Field objects all have
a Properties collection, which contains all the Property objects that apply to
their respective containing objects.

ADO objects possess properties where you set or retrieve values with common data
types like INTEGER, CHARACTER, or BOOLEAN. However, it's useful to think
of certain properties as returning values of data type "COLLECTION OBJECT."
The collection object, in turn, has methods to store and retrieve other objects
suitable for the collection.

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


For example, you can think of the Recordset object as having a Properties property
that returns a collection object. That collection object has methods to store and
retrieve Property objects describing attributes of that Recordset.
Events
ADO 2.0 introduces the concept of events to the programming model. Events are
notifications that certain operations are about to occur, or have already occurred.
You can use events, in general, to efficiently orchestrate an application consisting of
several asynchronous tasks.

The object model does not explicitly embody events, but represents them as calls to
event handler routines.

Event handlers called before the operation starts offer you the opportunity to
examine or modify the operation parameters, then either cancel or allow the
operation to complete.

Event handlers called after an operation completes notify you at the completion of
an asynchronous operation. ADO 2.0 introduces several operations that have been
enhanced to optionally execute asynchronously. For example, an application that
starts an asynchronous Recordset.Open operation is notified by an execution
complete event when the operation concludes.

There are two families of events:


• ConnectionEvents—Events are issued when transactions on a connection
begin, are committed, or rolled back; when Commands execute; and when
Connections start or end.

• RecordsetEvents—Events are issued to report the progress of data retrieval;


when you navigate through the rows of a Recordset object; when you change
a field in a row of a recordset, change a row in a recordset, or make any
change in the entire recordset.

ADO Programming Model with Objects


The goal of ADO is to gain access to, edit, and update data sources, and the
programming model embodies the sequence of activities necessary to accomplish
this goal. ADO provides classes and objects to perform each of the following
activities:
• Make a connection to a data source (Connection). Optionally, begin a
transaction.

• Optionally, create an object to represent an SQL command (Command).

• Optionally, specify columns, tables, and values in the SQL command as


variable parameters (Parameter).

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


• Execute the command (Command, Connection, or Recordset).

• If the command is row-returning, store the rows in a cache (Recordset).

• Optionally, create a view of the cache so you can sort, filter, and navigate the
data (Recordset).

• Edit the data, by either adding, deleting, or changing rows and columns
(Recordset).

• If appropriate, update the data source with changes from the cache
(Recordset).

• If a transaction was used, accept or reject the changes made during the
transaction. End the transaction (Connection).

ADO Object Model Summary


ADO Object Summary
Object Description
Connection Enables exchange of data.
Command Embodies an SQL statement.
Parameter Embodies a parameter of an SQL statement.
Recordset Enables navigation and manipulation of data.
Field Embodies a column of a Recordset object.
Error Embodies an error on a connection.
Property Embodies a characteristic of an ADO object.
ADO Collection Summary
Collection Description
All the Error objects created in response to a single failure on
Errors
a connection.
Parameters All the Parameter objects associated with a Command object.
Fields All the Field objects associated with a Recordset object.
All the Property objects associated with a Connection,
Properties
Command, Recordset or Field object.

ADO Event Handler Summary

ConnectionEvents Description
BeginTransComplete, Transaction Management—Notification
CommitTransComplete, that the current transaction on the
RollbackTransComplete connection has started, committed, or

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


rolled back.
Connection Management—Notification
WillConnect, ConnectComplete,
that the current connection will start, or
Disconnect
has started or ended.
Command Execution Management—
Notification that the execution of the
WillExecute, ExecuteComplete
current command on the connection will
start, or has ended.
Informational—Notification that there is
InfoMessage additional information about the current
operation.

RecordsetEvents Description
Retrieval Status—Notification of the
progress of a data retrieval operation, or
FetchProgress, FetchComplete
that the retrieval operation has
completed.
Field Change Management—Notification
WillChangeField, FieldChangeComplete that the value of the current field will
change, or has changed.
Navigation Management—Notification
WillMove, MoveComplete, that the current row position in a
EndOfRecordset Recordset will change, has changed, or
has reached the end of the Recordset.
Row Change Management—Notification
WillChangeRecord,
that something in the current row of the
RecordChangeComplete
Recordset will change, or has changed.
Recordset Change Management—
WillChangeRecordset, Notification that something in the
RecordsetChangeComplete current Recordset will change, or has
changed.

Solutions for Remote Data Access


The Issue
ADO enables your application to directly gain access to and modify data sources
(sometimes called a two-tier system). For example, if your connection is to the data
source that contains your data, then that is a direct connection in a two-tier system.

However, you may want to access data sources indirectly through an intermediary
such as Microsoft Internet Information Server (IIS). This arrangement is sometimes
called a three-tier system. IIS is a client/server system that provides an efficient way
for a local, or client, application to invoke a remote, or server, program across the

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Internet or an intranet. The server program gains access to the data source and
optionally processes the acquired data.

For example, your intranet Web page contains an application written in Microsoft®
Visual Basic®, Scripting Edition (VBScript), which connects to IIS. IIS in turn
connects to the actual data source, retrieves the data, processes it in some way, then
returns the processed information to your application.

In this example, your application never directly connected to the data source; IIS
did. And IIS accessed the data by means of ADO.
Note The client/server application doesn't have to be based on the Internet or an
intranet (that is, Web-based)—it could consist solely of compiled programs on a
local area network. However, the typical case is a Web-based application.
Because some visual control, such as a grid, check box, or list, may use the returned
information, the returned information must be easily used by a visual control.
You want a simple, efficient application programming interface that supports three-
tier systems, and returns information as easily as if it had been retrieved on a two-
tier system. Remote Data Service (RDS) is this interface.
The Solution
RDS defines a programming model—the sequence of activities necessary to gain
access to and update a data source—to gain access to data through an intermediary
such as Internet Information Server. The programming model summarizes the
entire functionality of RDS.

The programming model suggests an object model—the set of objects that


correspond to and implement the programming model. Objects possess methods that
perform some operation on data, and properties that either represent some attribute
of the data or control the behavior of some object method.

Associated with objects are events, which are notifications that some operation has
occurred, or is about to occur.

Basic RDS Programming Model


RDS addresses applications that exist in the following environment: A client
application specifies a program that will execute on a server and the parameters
required to return the desired information. The program invoked on the server
gains access to the specified data source, retrieves the information, optionally
processes the data, then returns the resulting information to your client application
in a form that it can easily use.

RDS provides the means for you to perform the following sequence of actions:

7. Specify the program to be invoked on the server, and obtain a way to refer to
it from the client. (This reference is sometimes called a proxy. It represents
the remote server program. The client application will "call" the proxy as if

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


it were a local program, but it actually invokes the remote server program.)

8. Invoke the server program. Pass parameters to the server program that
identify the data source and the command to issue. (The server program
actually uses ADO to gain access to the data source. ADO makes a
connection with one of the given parameters, then issues the command
specified in the other parameter.)

9. The server program obtains a Recordset object from the data source.
Optionally, the Recordset object is processed on the server.

10. The server program returns the final Recordset object to the client
application.

11. On the client, the Recordset object is put into a form that can be easily used
by visual controls.

12. Any modifications to the Recordset object are sent back to the server
program, which uses them to update the data source.

This programming model contains certain convenience features. If you don’t need a
complex server program to access the data source, and if you provide the required
connection and command parameters, RDS will automatically retrieve the specified
data with a simple, default server program.

However, if you need more complex processing you can specify your own custom
server program. For example, because a custom server program has the full power
of ADO at its disposal, it could connect to several different data sources, combine
their data in some complex way, then return a simple, processed result to the client
application.

Finally, if your needs are somewhere in between, ADO 2.0 now supports
customizing the behavior of the default server program.

The RDS Programming Model in Detail


The following elements are key parts of the RDS programming model:
• RDS.DataSpace

• RDSServer.DataFactory

• RDS.DataControl

• Event

RDS.DataSpace

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Your client application must specify the server and the server program to invoke. In
return, your application receives a reference to the server program and can treat
the reference as if it were the server program itself.
The RDS object model embodies this functionality with the RDS.DataSpace object.
The server program is specified with a program identifier, or ProgID. The server
uses the ProgID and the server machine's registry to locate information about the
actual program to initiate.
RDS makes a distinction internally depending on whether the server program is on
a remote server across the Internet or an intranet; a server on a local area network;
or not on a server at all, but instead on a local dynamic-link library (DLL). This
distinction determines how information is exchanged between the client and the
server, and makes a tangible difference in the type of reference returned to your
client application. However, from your point of view, this distinction has no special
meaning. All that matters is that you receive a usable program reference.
RDSServer.DataFactory
RDS provides a default server program that can either perform a SQL query
against the data source and return a Recordset object, or take a Recordset object
and update the data source.
The RDS object model embodies this functionality with the RDSServer.DataFactory
object.
In addition, this object has a method for creating an empty Recordset object that
you can fill programmatically, and another method for converting a Recordset
object into a text string to build a Web page.
With ADO 2.0, you can override some of the standard connection and command
behavior of the RDSServer.DataFactory with a DataFactory handler and a
customization file that contains connection, command, and security parameters.
The server program is sometimes called a business object. You can write your own
custom business object that can perform complicated data access, validity checks,
and so on. Even when writing a custom business object, you can create an instance
of an RDSServer.DataFactory object and use some of its methods to accomplish
your own tasks.

RDS.DataControl

RDS provides a means to combine the functionality of the RDS.DataSpace and


RDSServer.DataFactory, and also enable visual controls to easily use the Recordset
object returned by a query from a data source. RDS attempts, for the most common
case, to do as much as possible to automatically gain access to information on a
server and display it in a visual control.

The RDS object model embodies this functionality with the RDS.DataControl
object.
The RDS.DataControl has two aspects. One aspect pertains to the data source. If
you set the command and connection properties of the RDS.DataControl, it will
automatically use the RDS.DataSpace to create a reference to the default

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


RDSServer.DataFactory object. Then the RDSServer.DataFactory will use the
connection property value to connect to the data source, use the command property
value to obtain a Recordset from the data source, then return the Recordset object
to the RDS.DataControl.
The second aspect pertains to the display of returned Recordset information in a
visual control. You can associate a visual control with the RDS.DataControl (in a
process called binding) and gain access to the information in the associated
Recordset object, displaying query results on a Web page in Internet Explorer. Each
RDS.DataControl object binds one Recordset object, representing the results of a
single query, to one or more visual controls (for example, a text box, combo box,
grid control, and so forth). There may be more than one RDS.DataControl object on
each page. Each RDS.DataControl object can be connected to a different data
source and contain the results of a separate query.
The RDS.DataControl object also has its own methods for navigating, sorting, and
filtering the rows of the associated Recordset object. These methods are similar, but
not the same as the methods on the ADO Recordset object.
Events
RDS supports two of its own events, which are independent of the ADO Event
Model. The onReadyStateChange event is called whenever the RDS.DataControl
ReadyState property changes, thus notifying you when an asynchronous operation
has completed, terminated, or experienced an error. The onError event is called
whenever an error occurs, even if the error occurs during an asynchronous
operation.
Note The Microsoft Internet Explorer environment provides two additional events
to RDS—onDataSetChanged and onDataSetComplete.

RDS Programming Model with Objects


The goal of RDS is to gain access to and update data sources through an
intermediary like the Internet Information Server. The programming model
specifies the sequence of activities necessary to accomplish this goal. The object
model specifies the objects whose methods and properties affect the programming
model.
RDS provides the means to perform the following sequence of actions:
13. Specify the program to be invoked on the server, and obtain a way (proxy) to
refer to it from the client. (RDS.DataSpace)

14. Invoke the server program. Pass parameters to the server program that
identify the data source and the command to issue. (proxy or
RDS.DataControl)

15. The server program obtains a Recordset object from the data source,
typically by using ADO. Optionally, the Recordset object is processed on the
server. (RDSServer.DataFactory)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


16. The server program returns the final Recordset object to the client
application. (proxy)

17. On the client, the Recordset object is put into a form that can be easily used
by visual controls. (visual control and RDS.DataControl)

18. Changes to the Recordset object are sent back to the server and used to
update the data source. (RDS.DataControl or RDSServer.DataFactory)

The RDS Object Model Summary


Object Description
This object only contains a method to obtain a
server proxy. The proxy may be the default or a
custom server program (business object). The
RDS.DataSpace
server program may be invoked on the Internet, an
intranet, or local area network, or be a local
dynamic-link library.
This object represents the default server program.
RDSServer.DataFactory It executes the default RDS data retrieval and
update behavior.
• This object can automatically invoke the
RDS.DataSpace and
RDSServer.DataFactory objects.

• Use this object to invoke the default RDS


RDS.DataControl
data retrieval or update behavior.

• This object also provides the means for


visual controls to access the returned
Recordset object.

x---------------------------------------------------x

Visual Basic-6
21. Miscellaneous Projects

1. Creatiung forms during Run Time:

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Drag three command buttons in the form, size them caption them and locate them as
shown in the figure 1. Enter the code in the code window as shown in the figure 1a.
Save and run the project and see how forms are created, counted and cleared at run time.

Private Sub Command1_Click()


Dim x As New frmTest
x.Caption = "Test Form" & Forms.Count
x.Show
End Sub

Private Sub Command2_Click()


MsgBox "The Forms collection contains " & Forms.Count & " loaded forms."
End Sub

Private Sub Command3_Click()


Dim iLoop As Integer
For iLoop = Forms.Count - 1 To 0 Step -1
Unload Forms(iLoop)
Next iLoop
End Sub

Figure 1a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 1

2. This project is concerned with drag-drop operation. The data from the list box on the
left can be dragged and dropped in the list box named first destination at run time.
The input screen is as shown in the figure 2. Enter the codes as shown in the figure
2a.

Option Explicit

Private Sub Form_Load()

'Set the Drag icon of the control


'lstOrginal.DragIcon = imgList.ListImages("DRAG").ExtractIcon
End Sub

Private Sub lstDestination_DragDrop(Source As Control, X As Single, Y As Single)


If Source Is lstOrginal Then
If Source.ListIndex > -1 Then
lstDestination.AddItem Source.List(Source.ListIndex)

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Source.RemoveItem Source.ListIndex
End If
End If
End Sub

Private Sub lstOrginal_MouseDown(Button As Integer, Shift As Integer, X As Single, Y


As Single)
lstOrginal.Drag vbBeginDrag
End Sub

Private Sub lstOrginal_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As


Single)

lstOrginal.Drag vbEndDrag

End Sub

Figure 2a.

Figure 2

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


3. Calling a DLL Procedure:

Drag a picture box, 3 labels and 3 text boxes in the form, caption them, name them
and position them. The output window is shown in the figure 3.

Figure 3

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Open the code window for the general declarations section and enter the code as shown
in the figure 3a. This is the DLL declaration procedure. Enter the code in the command
buttons code window as shown in the figure 3b. Save and run the project.

Option Explicit

Private Declare Function GetComputerNameA Lib "kernel32" _


(ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function WNetGetUserA Lib "mpr" _
(ByVal lpName As String, ByVal lpUserName As String, lpnLength As Long) As
Long
Private Declare Function GetWinDir Lib "kernel32" Alias "GetWindowsDirectoryA" _
(ByVal lpBuffer As String, ByVal nSize As Long) As Long

Private Sub cmdGetComputerName_Click()


Dim strBuffer As String, lResult As Long
strBuffer = String(255, 0)
lResult = GetComputerNameA(strBuffer, Len(strBuffer))
If lResult <> 0 Then
strBuffer = Left(strBuffer, InStr(strBuffer, vbNullChar) - 1)
txtGetComputerName.Text = strBuffer
End If
End Sub

Private Sub cmdGetUserName_Click()


Dim strUserName As String, lResult As Long
strUserName = String(255, 0)
lResult = WNetGetUserA(vbNullString, strUserName, Len(strUserName))
If lResult = 0 Then
strUserName = Left$(strUserName, InStr(strUserName, vbNullChar) - 1)
txtGetUserName.Text = strUserName
End If

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


End Sub

Private Sub cmdGetWindowsDirectory_Click()


Dim strWindowsDir As String, lResult As Long
strWindowsDir = String(255, 0)
lResult = GetWinDir(strWindowsDir, Len(strWindowsDir))
strWindowsDir = Left$(strWindowsDir, lResult)
txtGetWindowsDirectory.Text = strWindowsDir
End Sub
Figure 3a
Option Explicit

Private Declare Function GetComputerNameA Lib "kernel32" _


(ByVal lpBuffer As String, nSize As Long) As Long
Private Declare Function WNetGetUserA Lib "mpr" _
(ByVal lpName As String, ByVal lpUserName As String, lpnLength As Long) As
Long
Private Declare Function GetWinDir Lib "kernel32" Alias "GetWindowsDirectoryA" _
(ByVal lpBuffer As String, ByVal nSize As Long) As Long

Private Sub cmdGetComputerName_Click()


Dim strBuffer As String, lResult As Long
strBuffer = String(255, 0)
lResult = GetComputerNameA(strBuffer, Len(strBuffer))
If lResult <> 0 Then
strBuffer = Left(strBuffer, InStr(strBuffer, vbNullChar) - 1)
txtGetComputerName.Text = strBuffer
End If
End Sub

Private Sub cmdGetUserName_Click()


Dim strUserName As String, lResult As Long
strUserName = String(255, 0)
lResult = WNetGetUserA(vbNullString, strUserName, Len(strUserName))
If lResult = 0 Then
strUserName = Left$(strUserName, InStr(strUserName, vbNullChar) - 1)
txtGetUserName.Text = strUserName
End If
End Sub

Private Sub cmdGetWindowsDirectory_Click()

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Dim strWindowsDir As String, lResult As Long
strWindowsDir = String(255, 0)
lResult = GetWinDir(strWindowsDir, Len(strWindowsDir))
strWindowsDir = Left$(strWindowsDir, lResult)
txtGetWindowsDirectory.Text = strWindowsDir
End Sub
Figure 3b

3. Project using ImageList Control:

Some nine icons are stored in each of the two Iimagelist controls and they are displayed one by one in
picture boxes. The Design window looks as in the figure 4.

Figure 4

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Open the codewindow of the command buttons and enter the code as shown in the figure
4a.

Option Explicit

Private Sub cmdLoadBitmap_Click()

If Val(txtBitmaps) = 0 Then
MsgBox "Enter a number between 1 and 9."
txtBitmaps.SetFocus
Exit Sub
End If

Image2.Picture = imgBitmaps.ListImages(Val(txtBitmaps)).Picture

End Sub

Private Sub cmdLoadIcon_Click()

If Val(txtIcons) = 0 Then
MsgBox "Enter a number between 1 and 9."
txtIcons.SetFocus
Exit Sub
End If

Image1.Picture = imgIcons.ListImages(Val(txtIcons)).Picture

End Sub

Figure 4a

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


During the design stage insert an array of nine images in each of the imagelist controls.
To add images to the imagelist control, click the properties page from the view menu.
The properties page appears as in the figure 5. Click on Images tab. You will get a
window for inserting images as shown in the figure 6. Click insert. You will get the
file open dialog box.. Select some 9 .ico files and 9 .bmp files to be added. Save and
run the project. The run mode window will look as in the figure 7.

Figure 5

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 6

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html


Figure 7

X====================================X

No license: PDF produced by PStill (c) F. Siegert - http://www.this.net/~frank/pstill.html

Potrebbero piacerti anche