VB Notes Iiibca
VB Notes Iiibca
CO Number
PS01 PS02 PS03 PS04
CO1 S M M --
CO2 M S L -
CO3 S M L M
CO4 S M M L
CO5 S M L L
59
UNIT-I
Welcome to VB:
Before we begin Visual Basic 6 programming, let us understand some basic concepts of
programming. A computer program is an organized list of instructions that, when executed, causes
the computer to behave in a predetermined manner. Without programs, computers are useless.
Therefore, programming means designing or creating a set of instructions to ask the computer to
carry out certain jobs, which normally are very much faster than human beings can do.
What is Visual Basic?
Visual Basicis a computer programming system developed and owned by Microsoft. Visual
Basic was originally created to make it easier to write programs for the Windows computer
operating system. The basis of Visual Basic is an earlier programming language called BASIC that
was invented by DartmouthCollege professors John Kemeny and Thomas Kurtz. Visual Basic is
often referred to using just the initials -VB. Visual Basic is easily the most widely used computer
programming system in the history of software.
Visual Basic was one of the first products to provide a graphical programming
environment and a paint metaphor for developing user interfaces. Instead of worrying about syntax
details, the Visual Basic programmer can add a substantial amount of code simply by dragging and
dropping controls, such as buttons and dialog boxes, and then defining their appearance and
behavior.
Although nota true object-oriented programming language in the strictest sense, Visual
Basic nevertheless has an object-oriented philosophy. It is sometimes called an Event-Driven
Language because each object can react to different events such as a mouse click.
Since its launch in 1990, the Visual Basic approach has become the norm for programming
languages. Now there are visual environments for many programming languages, including C, C++,
Pascal, and Java. Visual Basic is sometimes called a Rapid Application Development (RAD)
system because it enables programmers to quickly build prototype applications.
Visual Basic 1.0 (May 1991) was released for Windows at the Comdex/Windows World
trade show in Atlanta, Georgia.
Visual Basic 1.0 for DOS was released in September 1992.
Visual Basic 2.0 was released in November 1992.
Visual Basic 3.0 was released in the summer of 1993 and came in Standard and
Professional versions.
Visual Basic4.0 (August 1995) was the first version that could create 32-bit as well as 16-
bit Windows programs.
Visual Basic5.0 (February 1997), Microsoft released Visual Basic exclusively for 32-bit
versions of Windows. It was also used as an introductory form of Visual Basic: a regular
.exe project could be created and run in the IDE, but not compiled.
Visual Basic6.0 (Mid 1998) improved in a number of areas including the ability to create
web-based applications. Although the Visual Basic 6.0 development environment is no
longer supported, the runtime is supported on Windows Vista, Windows Server 2008 and
Windows
Features of Visual Basic
Visual Basic is not only a programming language, but also a complete Graphical
Development Environment.
This environment allows users with little programming experience to quickly develop
useful Microsoft Windows applications which have the ability to use OLE (Object Linking
and Embedding) objects, such as an Excel spreadsheet.
Visual Basic also has the ability to develop programs that can be used as a front end
application to a database system, serving as the user interface which collects user input and
displays formatted output in a more appealing and useful form than many SQL versions are
capable of.
Visual Basic's main selling point is the ease with which it allows the user to create nice
looking,graphical programs with little coding by the programmer, unlike many
otherlanguages that may take hundreds of lines of programmer keyed code.
As the programmer works in the graphical environment, much of the program code is
automatically generated by the Visual Basic program. In order to understand how this
happens, it is necessary to understand the major concepts, objects and tools used by Visual
Basic.
Visual Basic Editions
Visual Basic is available in three versions, each geared to meet a specific set of
development requirements. They are
Learning edition
Professional edition
Enterprise edition
Learning edition
The Visual Basic Learning edition allows programmers to easily create powerful
applications for Microsoft Windows 95 and Windows NT.
It includes all intrinsic controls, plus grid, tab, and data-bound controls.
Documentation provided with this edition includes Learn VB Now (a multimedia
CD-ROM title), a printed Programmer's Guide, online Help, plus Visual Basic
Books Online.
It also incorporates a limited subset of theJet engine's data access capabilities in the
Data control and special data-bound controls. These featuresallow you to access
existing databases, but do not provide for creating new databases or data
accessobjects.
Professional Edition
The Professional Edition provides computer professionals with a full featured set
of tools for developing solutions for others.
It includes all the features of the Learning edition, plus additional ActiveX
controls, including Internet controls, and the Crystal Report Writer.
Documentation provided with the Professional edition includes the Programmer's
Guide, online Help, the Component Tools Guide and the Crystal Reports for
Visual Basic User's Manual.
The Professional Edition includes all of the Data control features, and in addition
provides the full data access objects programming interface. Professional Edition
users can combine data access objects with the Data control to gain all of the
advantages of simplified data access while maintaining the flexibility of complete
programmatic control.
Enterprise edition
The Enterprise Edition allows professionals to create robust distributed
applications in a team setting.
Itincludes all the features of the Professional edition, plus the Automation
Manager, Component Manager, database management tools, the Microsoft
Visual SourceSafe project-oriented version control system, andmore.
Printed documentation provided with the Enterprise edition includes all Professional
edition pieces,plus the Building Client/Server Applications with Visual Basic
book and the SourceSafe User's Guide.
TheEnterprise Edition adds a number of powerful Client/Server tools to Visual
Basic's data access capabilities,including the Remote Data control (RDC)
specifically designed to access remote ODBC client/serverdatabases
The Visual Basic Philosophy
VB Control is an object that can be drawn on a Form object to enable or enhance user
interaction with an application.
Controls have Properties that define aspects their appearance, such as position, size and
color, and aspects of their behavior, such as their response to the user input.
Controls can respond to Events initiated by the user or set off by the system. For instance, a
code could be written in a CommandButton control's click event procedure that would load
a file or display a result.
In addition to properties and events, methods can also be used to manipulate controls from
code. For instance, the move method can be used with some controls to change their
location and size.
Most of the controls provide choices to users that can be in the form of OptionButton or
CheckBoxcontrols, ListBoxentries or ScrollBars to select a value.
Developing an Application
Steps in Building a Visual Basic Application
Step 1: Design the interface
Step 2: Set properties of the controls (Objects)
Step 3: Write the event procedures or code
First thing to do is to create a Directory where you will store all your VB Projects. Call it
VBApps, for example. Then start VB. The first screen will ask whether you want to open a new
project or an existing one - it's obviously a new one and it will be a Standard EXE. Then,
maximize all the windows. Now, save your project. It will first ask you to save the form with the
extension .frm - and then the Project –with extension .vbp.
To get a control you go to the Toolbox, click on the control you want, come back to the
Form and click and drag the control to the size and position you want. To Change the properties of
the window go toProperties Window. It will open by pressing F4 (or) click view->properties.
We must write code in response to user input or event in the code window. To go to the
code window press F7 (or) double click on Form1. The top of the source code window consists of
a list of objects and their associated events or procedures.
A framework will appear while we click the control & within it we enter our own code
private Sub Form_Load ()
Form1.show
Print ―Welcome to Visual Basic‖
End Sub
- TextBox:
- It is used to accept the user input in text format (or) to display the results. It is also called
as an Edit Field (or) Edit control. Users can edit the information at runtime (or) at design
time
- PictureBox
- It is used to display the picture. The picture may be jpeg (or) gif files. It clips the picture if
the control isn‘t large enough to display the entire image
- Label Box
It displays text which is not edit by the user
- Option Button
- This control is used to select only one option from multiple choices
- Frame
-This control allows the user to create a graphical (or) functional grouping of controls. To
group controls, first draw the frame after that draw controls inside the frame
- ListBox
-It is used to display list of item for which user can choose anyone item. Limitation of this
control is that we cannot enter new item at run time
- Combo Box
-User can choose an item or enter new item in the textbox.New values can be added to the
existing data
- Data Control
-It is used to access the information from the data base
- HScrollBar
-It is a graphical tool for quickly navigating through a long list of items or a large amount of
information
- VScrollBar
- It is a graphical tool for quickly navigating through a long list of items or a large amount
of information
- Timer
- It is used to keep track of the number of minutes or hours
- Command Button
- The user can choose to carry out a command. When the user click on the button the
computer will perform the task associated with the button
- CheckBox
-It is used when the user can choose more than one choices
- Image Control
-It is used to display the pictures. We can stretch the picture to the size of the image control
The above image will be displayed in the comment's value type some comments company
name name etc...
The Title tag represents the caption you will see if you press Control + Alt + Del. And the
icon is the icon that will be available on the execute icon. As you can see it is quite simple
to understand.
All the comments, data and name appear when you click on the compiled (execute) exe and
click properties
Saving your visual basic project
Save your work to disk. Use the Windows Explorer or any desktop windows to
check that all files have been saved.
There should be one Visual Basic Project (.VBP) file and separate Form (.FRM)
and Module (.BAS) files for each form and module used in the current project.
Button Properties for reference
, Command Button & labels properties
Property Description
Name The name of the object so you can call it at runtime
This specifies the command button's background color. Click the BackColor's
BackColor palette down arrow to see a list of common Windows control colours, you must
change this to the style property from 0 - standard to 1 – graphical
Determines whether the command button gets a Click event if the user presses
Cancel
escape
Caption Holds the text that appears on the command button.
Determins if the command button responds to an enter keypress even if another
Default
control has the focus
Determines whether the command button is active. Often, you'll change the enable
Enable
property at runtime with code to prevent the user pressing the button
Produces a Font dialog box in which you can set the caption's font name , style
Font
and size.
Height Positions the height of the object - can be used for down
Left Positions the left control - can be used for right
MousePointer If selected to an icon can change the picture of the mouse pointer over that object
Hold's the name of an icon graphic image so that it appears as a picture instead of
Picture
a Button for this option to work the graphical tag must be set to 1
This determins if the Command Button appears as a standard windows dialog
Style
box or a graphical image
Tab index Specifies the order of the command button in tab order
Whether the object can be tabbed to ( this can be used in labels which have no
Tab Stop
other function )
If the mouse is held over the object a brief description can be displayed (for
Tool Tip Text
example hold your mouse over one of the above pictures to see this happening
Visible If you want the user to see the button/label select true other wise just press false
Width Show the width of the object
Procedures/Events Box
Object Box
Split Bar
Separator
Margin
indicator
The object box has the list of all controls which are placed on the form. The first item to
be displayed is ‗General‘. The names of the control are sorted alphabetically. The name
displayed will be names that we have specified against the ‗Name‘ property for the
control.
Ex. Command1 named as CmdOne
Procedure / event box
The Event box has the list of all events which match to the selected controls; normally it
will load the default event for the control.
Ex. If we select CmdOne means it will load the default event Click Event
Split bar
It is used to view different parts of the code. Each part can be scrolled independently. By
dragging the bar we can resize the different part of the code. To close the split bar
simply double click on the bar or drag it to top or the bottom of the code window.
Margin indicator bar
The gray area on the left side of the window is margin indicator which is used to
indicate the specific locations of the code at the run time for debugging propose.
Procedure view icon
It is used to display the selected procedure. Only one will display procedure at a time.
Full module view icon
It is used to display the entire code in the module.
Separator
It is a horizontal line that separates tow procedures.
The Anatomy of Procedure
It offers different types of procedures to execute small sections of coding in Aplications.
Visual Basic programs can be broken into smaller logical components called Procedures.
Procedures are useful for condensing repeated operations such as the frequently used calculations,
text and control manipulation etc.
The benefits of using procedures in programming are:
It is easier to debug a program a program with procedures, which breaks a program into
discrete logical limits.
Procedures used in one program can act as building blocks for other programs with slight
modifications.
A Procedure can be Sub, Function or PropertyProcedure.
Sub Procedures
A sub procedure can be placed in standard, class and form modules. Each time the procedure is
called, the statements between Sub and End Sub are executed. The syntax for a sub procedure is as
follows:
[Private | Public] [Static] Sub Procedurename [( arglist)]
[ statements]
End Sub
arglist is a list of argument names separated by commas. Each argument acts like a variable in the
procedure. There are two types of Sub Procedures namely general procedures and event procedures.
Ex.Private SubSum (a as integer, b as integer)
Sum = a + b
End sub
Event Procedures
An event procedure is a procedure block that contains the control's actual name, an
underscore (_), and the event name. The following syntax represents the event procedure for a
Form_Load event.
Private Sub Form_Load()
FrmNumbers.Enabled = False
FrmOperator.Enabled = False
End Sub
Event Procedures acquire the declarations as Private by default.
Function Procedures
Functions are like sub procedures, except they return a value to the calling procedure. They
are especially useful for taking one or more pieces of data, called arguments and
performing some tasks with them.
Then the function returns a value that indicates the results of the tasks complete within the
function.
[Private | Public] [Static] FunctionFunctionName [( arglist)] as [return type]
[ statements]
End Function
The following function procedure calculates the third side or hypotenuse of a right triangle,
where A and B are the other two sides.
It takes two arguments A and B (of data type Double) and finally returns the results.
Function Hypotenuse (A As Double, B As Double) As Double
Hypotenuse = sqr (A^2 + B^2)
End Function
The above function procedure is written in the general declarations section of the Code
window.
A function can also be written by selecting the Add Procedure dialog box from the Tools
menu and by choosing the required scope and type.
Property Procedures
A property procedure is used to create and manipulate custom properties. It is used to create
read only properties for Forms, Standard modules and Class modules.
Visual Basic provides three kinds of property procedures-
Property Let procedure that sets the value of a property,
Property Get procedure that returns the value of a property, and
Property Set procedure that sets the references to an object.
Editor Features
The features of VB text editor are:
The VB development team has lavished great effort on making editing in VB as easy yet efficient
as possible.
The first thing you notice is that the editor uses color coding: comments are in green; VB
keywords are in blue;and most other code is in black.
Even more important is the fact that VB has a very smart text editor. Every time a line of
code is entered, VB checks its syntax and immediately flags any errors.
VB's Intelligence feature gives users lots of help in getting the syntax right in the first place.
Aswe started to type the text2 property "text", the Intelligence combo popped up with all
the possible properties and had honed in on the right suggestion by the time we had type
"te". All I had to do was to hit the Tab key and Intelligence filled in the rest of the
command.
Completion of the line it checks the syntax and, if correct, immediately fancy formats the
line. Fancy formatting includes adding blank spaces around operators (like "+", "-", "*",
etc), auto-indenting code blocks and capitalizing variable names that have been entered in
all lowercase. The latter is reason for including at least one capital letter in all VB names.
Then if you have misspelled the name its capital letter does not appear when the line is
immediately fancy formatted - so you have a quick way to catch misspellings.
The Decision Making Statements
If...Then selection structure
The If...Then selection structure performs an indicated action only when the condition is True;
otherwise the action is skipped.
Syntax of the If...Then selection
If<condition>Then
statement
End If
Example
If average>75 Then
txtGrade.Text = "A"
End If
Example
If average>50 Then
txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If
Do Until works almost exactly like the Do While loop except that the Do Until loop continues
executing the body of the loop until the condition is true.
Like the Do While, the Do Until is a multiline looping statement that can execute a block of
code that's one or more lines long.
Do Until (condition)
Block of one or more Visual Basic statements
Loop
Remember that the condition must be false for the loop to continue.
You can use the Do While or the Do Until for almost any loop.
Example:
Do until counter>1000
num.Text=counter
counter=counter+1
Loop
The For loop
The For loop is probably the most popular loop statement in Visual Basic , here is the syntax of the
For loop.
Forindex = startToend [Step step]
[ Statements ]
[ Exit For ]
Next [index]
The For is the keyword you use to start the loop.
Indexis a user defined numeric variable that the loop uses as a counter .
startis the number from which the loop starts from .
To is the keyword which separates the start and end numbers .
endis the number at which the loop stops .
Step is an optional keyword indicating the loop should step .
stepis the size of increment / decrement the step should have (this can be a negative
number)
Next is the keyword that completes the loop .
index is used to identify which index is updated by the Next keyword .
Here are some general points about For loops that I have read in books that you may want to use.
The index value is usual called something clear like intCounter .
The index after the Next is optional but helps reading of your code.
Likewise if your Step value is 1 you can omit the Step 1 from the end of your because the
default value is 1 , but it is best kept for clarity .
Example:
Private Sub Form_Load()
Ford = 1 To31Step 1
CmbDay.addItem(d)
Next i
Form = 1 To12Step 1
CmbMonth.addItem(m)
Next i
Fory = 1 Toyear(now)
CmbYear.addItem(y)
Next
End Sub
Visual Basic's Iteration or Loop Statements
Loop type Examples Notes
Do While/Until .. Exit Do .. Loop Do Until cnt> 100 This loop checks the
Conditional 0 or more iterations cnt = cnt + 1 ... condition first then proceeds
loop Loop through loop if true.
Do .. Exit Do .. Loop While/Until Do This loop does at least one
Conditional 1 or more iterations Input Line #fileNo, buffer iteration then checks if more
loop Loop While Not EOF(fileNo) are needed.
For Each .. Exit For .. Next For Each dVariant In dblArray The "In" group can be an
Count through an array or sum = sum + dVariant array or any collection of
collection Next objects.
The Step value is optional
For ii= 100 To 0 Step -5
For .. Exit For .. Next and defaults to 1. The counter
if dval(ii) > 100 Then Exit For
Classic counting loop variable must be numeric but
Next ii
not an array.
While IsNumeric(Mid(InString, ii, While loop has been
While ... Wend 1)) superseded by Do
Conditional loop ii = ii + 1 While/Until - for example,
Wend there is no Exit.
DirList box
DriveList box
1. Copying Files
The "FileCopy" command has the limitation that you cannot use wildcards to
specify multiple files. "FileCopy" can copy files locally or over a network, as shown in the
following example :
Syntax: FileCopy Source, Destination
Example:
'The following line copies a file while changing its name :
FileCopy"D:\DRAWING\TEST.DWG", "C:\BACKUP\TEST-BACK.DWG"
'The following lines of code use a network path for the source file :
Dim sDest As String
Dim sSource As String
sSource = "\\MYSERVER\DRAWINGS\TEST.DWG"
sDest = "C:\BACKUP\TEST-BACK.DWG"
FileCopysSource, sDest
The "FileCopy" statement automatically overwrites an existing file, unless the
file is read-only or locked open by another application.
2. Deleting Files
Visual Basic also allows you to delete files by using the "Kill" statement. "Kill"
can use wildcards to specify multiple files, as in the following example:
Syntax: Kill Path
Example: Kill "D:\DRAWINGS\*.DWG"
3. Renaming Files
The "Name" statement is like the MS-DOS "RENAME" command but can be used on
only one file at a time.
Syntax: Name oldname As newname
You can also use "Name" like the "MOVE" command in MS-DOS if the specified paths are
different:
'Moves the files to a new directory
MkDir "C:\BACKUP\TEST-BACK.DWG"
Name "D:\DRAWING\TEST.DWG" As "C:\BACKUP\TEST-BACK.DWG"
4. Crating and removing Directory
The "MkDir" statement is used to create a new directory.
Syntax: MkDir Path
Example: MkDir"D:\IIIBCA-E‖
The "RemDir" or ―RmDir‖ statement is used to remove directories.
Syntax: RemDir Path orRmDir
Example: RmDir"D:\IIIBCA-E‖
5. Setting the Current Directory
The "ChDir" and "ChDrive" statements can use to set the current working directory on each
drive and switch between current drives, eliminating the need to specify the full path for each
file operation:
A file opened for random access is assumed to be composed of a set of identical-length records, or
sets of fields containing information. You can employ user-defined types to create records made up of
numerous fields, each of which can have different data types. Data is stored as binary information.
Binary access allows you to use files to store data in any form that suits your needs, whether it is
numeric, string, or both. Binary access is similar to random access except that no assumptions are
made about data type or record length. However, you must know precisely how the data was written
to the file to retrieve it correctly. For example, if you store a series of names and phone numbers, you
need to remember that the first field (the name) is text and the second field (the phone number) is
numeric.
The Type statement creates a new data type; in this case, it's PhoneRec. Once it's been defined, the
new type can be used like any other type, String or Integer, etc. to declare a variable:
Dim InRecord As PhoneRec
The individual fields in the structured variable can be accessed using dot notation:
Label5.Caption = InRecord.Fname
txt_city.Text = InRecord.City
When you define the fields within the new type, it's important to determine the length of each string.
Random access is sensitive about record lengths. When you define a String field like: FnameAs
String * 15 you determine that the size of the field will always be 15 characters. This is important
for the processing to work properly! Just make sure that the size you assign is big enough to handle
most situations. You do not have to worry about the Integer field because its size is standard.
Writing and Reading records
The command to write records to the Random file is Put. Its format is:
Put #Filenumber, [RecordNumber], Variable
RecordNumber is optional and, if it's omitted, variable is written in Next record position after last Put
or Get statement.
The command to read records from a Random file is: Get. Its format is:
Get #FileNumber, [RecordNumber], Variable
If RecordNumber is omitted, next record is read from the file.
File System Objects (FSO)completely recast Visual Basic‘s fundamental powers over disk storage
in an object-oriented mold. It makes file access and management considerably easier, even though it
isn‘t quite complete.
The object-oriented file access and management system, called File System Objects (FSO).
This isn‘t one of the flashier additions to the new version of Visual Basic, and it certainly has not
gotten the same attention as, say, ActiveX Data Objects or Dynamic HTML. Even so, it‘s an
important improvement to the language, one that you should begin using in your own programs as
soon as possible. FSO really doesn‘t let you do anything that cannot be done with the old file-oriented
commands, but it makes many tasks much easier. Perhaps most important is that FSO moves file
access and manipulation from the realm of procedural programming to the modern realm of object-
oriented programming, with all the advantages that entails.
There is, however, one fly in the ointment. While the FSO framework for file management (creating
folders, moving and deleting files, and so on) seems to be complete, the file access part of FSO
(writing data to and reading data from files) is only partially complete. To be precise, you can read
and write only sequential text files—for random access and binary files, you are still limited to the
traditional Basic statements. I am sure this limitation will be corrected soon, but for now you‘ll just
have to live with it.
Text File Access with FSO
The top class in the FSO hierarchy is the FileSystemObject class. To read or write a text file, you
must first create an instance of this class:
Dim myFSO
Set myFSO = CreateObject("Scripting.FileSystemObject")
The following alternate syntax accomplishes the same thing:
Dim myFSO As New Scripting.FileSystemObject
The Scripting qualifier identifies the library in which the FileSystemObject class is defined. To use
the class, you do not need to select the Microsoft Scripting Runtime library in the Visual Basic
References dialog box, but doing so will give you access to the classes, methods, and properties in the
Object Browser. (If you are not familiar with the Object Browser, you owe it to yourself to find out; it
is a great source of information about classes.)
After creating an instance of the FileSystemObject class, the next step is to create a TextStream
object. A TextStream object is nothing more than a regular text file enclosed in an FSO wrapper.
The FileSystemObject has two methods for creating TextStream objects:
CreateTextFile creates a new text file. If a file of the same name already exists, it is
overwritten.
OpenTextFile opens a text file for reading and/or writing. If the file already exists, new data
is appended to existing data.
The syntax for these methods is similar. In these examples, assume that myFSO is a
FileSystemObject and that it has been declared as a type Variant or Object. The first line of code
creates a new file, and the second line opens an existing file:
Set ts = myFSO.CreateTextFile(filename[, overwrite[, unicode]])
Set ts = myFSO.OpenTextFile(filename[, iomode[, create[,format]]])
Filename is a string expression specifying the name (including path information) of the file.
The overwrite argument is either True or False, indicating whether an existing file will be
overwritten. If this argument is omitted, the default is False. If overwrite is False and
filename already exists, an error occurs. You can trap this error to permit the user to verify
file overwrites.
Set unicode to True to create a Unicode file, or False (the default) for an ASCII file.
Set iomode to the constants ForReading or ForAppending to read the file or write data to
the end of the file, respectively. A file opened using ForReading cannot be written to.
Set create to True or False to specify whether a new file will be created if the file named in
the filename argument does not exist. The default is False.
The format argument is a tristate argument (that is, one that can take on one of three possible
values) that determines the format of the file:
TriStateTrue opens the file as Unicode.
TriStateFalse (the default) opens the file as ASCII.
TristateUseDefault uses the system default format setting.
Another way to obtain a TextStream object is to create a File object and then use its
OpenAsTextStream method. This method works with existing files only. Creating a File object is
done like this, assuming that myFSO is a FileSystemObject:
Dim f
Set f = myFSO.GetFile(filename)
If the file does not already exist, you can take the following approach, using CreateTextFile to create
the file before creating the File object:
myFSO.CreateTextFile filename
Set f = myFSO.GetFile(filename)
After creating the File object, you can invoke the Open-AsTextStream method. The syntax is:
f.OpenAsTextStream([iomode, [format]])
The iomode and format arguments are the same as described above for the CreateTextFile and
OpenTextFile methods. Here‘s the code necessary to create a TextStream object associated with an
existing file DEMO.TXT for reading, using the OpenAsTextStream method:
Dim myFSO, f, ts
Set myFSO = CreateObject("Scripting.FileSystemObject")
Set f = myFSO.GetFile("demo.txt")
Set ts = f.OpenAsTextStream(ForWriting, _
TristateUseDefault)
Once you have created a TextStream object, you use its properties and methods to write and read
text. The object‘s properties are listed in Table 1. In reading this table, be aware that the TextStream
object always has a current character position, also called the file pointer, that indicates where the
next read or write operation will take place. All of these properties are read-only.
Table 1. Properties of the TextStream object.
Property Description
True if the file pointer is at the end of a line; False otherwise. This property
AtEndOfLine applies only to TextStream files that are open for reading; otherwise, an error
occurs.
True if the file pointer is at the end of the file; False otherwise. This property
AtEndOfStream applies only to TextStream files that are open for reading; otherwise, an error
occurs.
Returns the column number of the file pointer. The first character on a line is at
Column
column 1.
Line Returns the current line number.
The TextStream object has a number of methods to read and write data. These methods are described
in Table 2.
Table 2. Methods of the TextStream object.
Property Description
Closes the file associated with the TextStream object. Always execute the
Close
Close method when you are done reading/writing the file.
Read(n) Reads the next n characters from the file and returns the resulting string.
ReadAll Reads the entire file and returns the resulting string.
Reads an entire line (up to, but not including, the newline character) from a
ReadLine
TextStream file and returns the resulting string.
Skip(n) Skips ahead (moves the file pointer) by n characters.
SkipLine Skips to the beginning of the next line.
Write(s) Writes the string s to the file. No extra or newline characters are added.
WriteBlankLines(n) Writes n blank lines to the file.
WriteLine(s) Writes the string s to the file followed by a newline character.
Be aware that certain of these methods are applicable only when the file has been opened for reading
or writing. If you try to use a method that is inappropriate for the file‘s mode, an error will occur.
The Copy method copies the folder and its contents to a new location. The syntax is as follows
(assuming f to be a Folder object):
f.Copy destination[, overwrite]
The destination argument specifies the destination where the folder is to be copied to.
Set overwrite to True (the default) to overwrite existing files or folders, or to False
otherwise. Note that you can also copy a folder using the FileSystemObject‘sCopyFolder
method.
The Move method moves the folder and its contents from one location to another. The syntax is:
f.Move destination
destination specifies the destination where the folder is to be moved to. You can also move
folders with the FileSystemObject‘sMoveFolder method.
The Delete method deletes a folder and its contents. The syntax is:
f.Delete [force]
The optional force argument specifies whether files or folders with the read-only attribute set should
be deleted (force = True) or not (force = False, the default). You can also delete folders with the
FileSystemObject‘sDeleteFolder method.
File Handling (Generic)
Dir - Returns a filename that matches a pattern
temp$ = Dir ("*.*")
CurDir - Returns the current directory
temp$ = CurDir
MkDir - Creates a directory
mkdir ( "newdirectoryname" )
ChDir - Changes the current directory to a new location
chdir ( "newdirectoryname" )
ChDrive - Changes the current drive
ChDirve "A"
RmDir - Removes the indicated directory
rmdir ( "directoryname" )
Freefile - Returns an unused file handle
i = freefile
Open - Opens a file for access, locking it from other applications
open "filename" for input as #1
Close - Closes a file so that other applications may access it
close #1
LOF - Returns the length of a file in bytes
i = lof ( #1 )
EOF - Returns a boolean value to indicate if the end of a file has been reached
statusvariable = eof ( #1 )
Name As - Renames a file
name "filename1" as "filename2"
Kill - Deletes a file
kill "filename"
Fileattr - Returns attribute information about a file
i = int ( tempvariable )
GetAttr - Returns attributes of a file or directory
i = GetAttr("c:\windows\temp")
SetAttr - Sets the attributes of a file
SetAttr pathname, vbHidden
Reset - Closes all disk files opened by the OPEN statement
Reset
FileDateTime - Returns data file was created or last edited
FileDateTime ( filename )
FileLen - Returns length of file in bytes
FileLen ( filename )
FileCopy - Copies a file to a new name
FileCopysourcefile, destinationfile
Lock - Controls access to a part or all of a file opened by OPEN
Lock #1
UnLock - Restores access to a part or all of a file opended by OPEN
UnLock #1
Width # - Set the output line width used by the OPEN statement
Width #2, 80
Menus
Every window applicationHas menu bar. The menu gives the users access to functions that are
not defined as controls (editing, formatting, etc) and also repeats certain functions that are coded as
controls (for exampleExit button).
Menus offer a variety of functionalities to define the application:
o Sub-menus,
o Checked items,
o Enabled/disabled functions,
o Toolbar icons
The VB IDE that you are using certainly displays all of those tools, as in the diagram below.
Creating a Menu
The File menu, shown below, will have the following level-two items below it: New, Open, Save,
Save As, Print, and Exit. Note that separator bars appear above the Save, Print, and Exit items. The
File menu, shown below, will have the following level-two items below it: New, Open, Save, Save
As, Print, and Exit. Note that separator bars appear above the Save, Print, and Exit items.
The Help menu contains just one level-two item below it, About.
To build a menu for use with your VB program, you use the Menu Editor, which appears as an icon
in the toolbar of the VB IDE. It is the circled item in the screen shot below:
Alternatively, you can invoke the Menu Editor from the Tools menu item as shown below:
2. For "Caption", type &File (by placing the ampersand to the left of the "F", we establish "F" as an
access key for the File item it enables the user to drop down the File menu by keying "Alt+F" on
the keyboard in addition to clicking the "File" item with the mouse).
For "Name", type mnuFile.
Your Menu Editor screen should look like this:
3. Click the "right-arrow" button (shown circled below). A ellipsis (...) will appear as the next item
in the menu list, indicating that this item is a level-two item (below "File").
For "Caption", type &New; for "Name", type mnuNew, and for "Shortcut", select Ctrl+N. By
specifying a shortcut, you allow the user to access the associated menu item by pressing that key
combination. So here, you are providing the user three ways of invoking the "New" function:
Clicking File, and then clicking New on the menu;
keying Alt+F,N (because we set up an access key for "N" by placing an ampersand to left of
"N" in "New"); or
keyingCtrl+N. At this point, your Menu Editor screen should look like this:
6. For "Caption", type &Save; for "Name", type mnuSave, and for "Shortcut", select Ctrl+S. Your
Menu Editor screen should look like this:
Click the Next button.
Like this add till the Exit
For "Caption", type &Help; and for "Name", type mnuHelp. Your Menu Editor screen should look
like this:
Click the Next button.
8. Click the "right-arrow" button to create a level-two item below "Help". For "Caption", type
&About; and for "Name", type mnuAbout. Your Menu Editor screen should look like this:
9. At this point, we are done creating our menu entries, so click the OK button. That will dismiss the
menu editor and return focus to the VB IDE.
10. Back in the VB IDE, your form will now have a menu, based on what you have set up in the
Menu Editor. If you click on a top-level menu item (File for example), the level-two menu will
drop down:
11. Click on the Newmenu item. The code window for the mnuFileNew_Click event opens, as
shown below. Note: Click is the only event that a menu item can respond to.
12. Code similar MsgBox statements for the Open, Save, Save As, and Print menu items:
13. For the About menu item Click event, code as shown below:
Private Sub mnuHelpAbout_Click()
MsgBox "Menu Demo" &vbCrLf& "Copyright AVS III BCA E", , "About"
End Sub
14. Run the program. Note how the code executes when you click on the various menu items. Also
test the use of the access keys (e.g., Alt+F, N) and shortcut keys (e.g., Ctrl-O).
UNIT-III
MDI Applications
Why MDI Forms?
MDI (Multiple Document Interface) is a Microsoft Windows programming interface for
creating an application that enables users to work with multiple documents at the same time.
Each document is in a separate space with its own controls for scrolling.
The user can see and work with different documents such as a spreadsheet, a text document,
or a drawing space by simply moving the cursor from one space to another.
An MDI application is something like the Windows desktop interface since both include
multiple viewing spaces.
However, the MDI viewing spaces are confined to the application's window or client area .
Within the client area, each document is displayed within a separate child window .
MDI applications can be used for a variety of purposes - for example, working on one
document while referring to another document, viewing different presentations of the same
information, viewing multiple Web sites at the same time, and any task that requires multiple
reference points and work areas at the same time
MDI Forms
The multiple-document interface (MDI)allows you to create an application thatmaintains multiple
forms within a singlecontainer form.
Usage of MDI Application
A typical use of a standard form in an MDIapplication is to display a modal dialog box.
When menu options are common w.r.t. thevarious forms
Difference between MDI Forms and Ordinary Form
They follow the parent-child relationshipdisplayed by the application anddocument windows
in the document centeredapplications.
You can't place a control directly on a MDIform unless that control has an Alignproperty
(such as a picture box control) orhas no visible interface (such as a timercontrol).
Run-Time Features of MDI Forms
All child forms are displayed within the MDI form's workspace.The user can move and size
child forms like any other form;however, they are restricted to this workspace.
When a child form is minimized, its icon appears on the MDIform instead of the taskbar.
When the MDI form is minimized, theMDI form and all of its child forms are represented by
a singleicon. When the MDI form is restored, the MDI form and all thechild forms are
displayed in the same state they were in beforebeing minimized.
When a child form is maximized, its caption is combined withthe caption of the MDI form
andis displayed in the MDI form'stitle bar as shown below.
By setting the AutoShowChildren property, you can displaychild forms automatically when
forms are loaded (True), or loadchild forms as hidden (False).
The active child form's menus (if any) are displayed on the MDIform's menu bar, not on the
child form.
Steps for creating MDIApplications
Open the project.
Create a parent form by Project>>Add MDI Form
Add normal form and set its MDIChild property to True
Write the code for automation on the parent and childform as per requirement.
The Form that you have been using so far are single form. In Visual Basic you can use Multiple
Document Interface (MDI) Form, a form that can contain multiple forms. Here is how to create MDI
Form:
Loading MDI From and Child Forms
1. Start Visual Basic Standard Exe project.
2. In the Project Window, do Right Click and it show a pop up menu, choose Add > MDI Form.
In the dialog window, press Open button
3. Go to Form1. Change the MDI Child Property of Form1 (and all other forms if exist) into
True. This will make Form1 as child form instead of parent
4. In the VB menu, select Project > Project1 Properties. In the General Tab, StartUp Object,
select MDI Form1, then OK. This is to make VB run for the first time by calling the MDI
Form.
5. Run the program
Debugging Tips
Debugging is the process that you use to find and resolve errors, or bugs, in your Visual Basic
for Applications code. There are three types of errors that you can encounter: compile-time
errors, run-time errors, and logic errors.
Logic errors occur when the application does not perform as intended and produces incorrect
results.
Microsoft Access provides debugging tools that enable you to step through your code one line
at a time, to examine or monitor the values of expressions and variables, and to trace
procedure calls.
All of these aid in finding and eliminating logic errors.
The general procedure for debugging Visual Basic for Applications code is to break larger
procedures into smaller subprocedures to verify that the individual steps in each subprocedure
work correctly, and then to combine the subprocedures one by one until the code works
correctly.
There are several different methods that you can use to debug your Visual Basic for
Applications code. The main ones are these:
1. Use the Immediate Window
You can use the Immediate window to run individual lines of Visual Basic for Applications code or
to check the values of variables. In the Immediate window, you can:
Test and debug Function and Sub procedures.
Check the value of a field, a control, a property setting, a variable, or an expression.
Display the result of an expression when the code is running.
To display the Immediate window in the Visual Basic Editor, either click Immediate Window on the
Debugmenu , or press CTRL+G.
Do WhileintNumber> 0
PyrNum = PyrNum + intNumber
intNumber = intNumber - 1
Loop
End Function
3. On the View menu, click Immediate Window.
4. Type ?PyrNum(3), and then press ENTER.
For example, to check the values of two arguments passed to the DoSomeCalcs() function,
place the following sample Debug.Print statement at the beginning of the function as follows:
Function DoSomeCalcs(Arg1 as Single, Arg2 as Single)
Debug.Print "Arguments Passed: " & Arg1 &" and " & Arg2
.
.
If the values of the arguments are not correct, their values are captured before the function
runs and errors occur.
You can also use the Debug.Print statement at the beginning of each function if you have a
complex application and you are not sure which function might be causing a problem. This
lets you check the Immediate window to see the order in which functions are called. You can
also click Call Stack on the View menu to list the current function call stack and to show the
order in which the functions are called, as discussed below.
In decision structures, you can check that you are using the correct logic for the function, for
example:
Debug.Print is a convenient way to monitor more than one value as well as to verify that the
loop is executing the number of times you expect. If the loop executes three times, you should
see three output lines in the Immediate window.
For example, you can modify the PyrNum() function like this
Public Function PyrNum(ByValintNumber As Integer)
Dim intPyr As Integer
' Returns the pyramid value of an integer, which is
' the sum of the integer and all smaller integers greater than 0
Do WhileintNumber> 0
PyrNum = PyrNum + intNumber
Debug.PrintintNumber, PyrNum
intNumber = intNumber - 1
Loop
End Function
to log the changes in PyrNum and intNumber as the loop executes.
Run this function in the Immediate window by typing ?PyrNum(3) and pressing ENTER. You
will see the following output:
3 3
2 5
1 6
6
The final 6 is the return value of the function, and not output from the Debug.Printstatement.
In SQL Where clauses, you can check the values of criteria.
For example, the following function creates a dynaset from a SQL statement. A problem in a
SQL statement (such as in this function), can be difficult to locate. However, this function
uses Debug.Print to display the SQL statement as Microsoft Access sees it and uses it:
Function TestMe()
Dim db As DAO.Database, rs As DAO.Recordset
Dim empnum As Long
Dim strSQL As String
Set db = CurrentDb()
empnum = 5
strSQL = "select * from orders where [employeeid]=empnum"
Debug.PrintstrSQL
Set rs = db.OpenRecordset(strSQL)
End Function
Run this function in the Immediate window by typing ?TestMe() and then pressing ENTER.
You will see the following appear in the Watches window:
select * from orders where [employeeid]=empnum;
This Where condition shows [employeeid] = empnum, not [employeeid] = 5 as you assigned
it. The cause is that the variable empnum needs to be exposed outside the SQL string. To fix
this particular problem, change the Where condition to concatenate the empnum variable, as
follows:
Function TestMe()
Dim db As DAO.Database, rs As DAO.Recordset
Dim empnum As Long
Dim strSQL As String
Set db = CurrentDb()
empnum = 5
strSQL = "select * from orders where [employeeid]=" &empnum& ";"
Debug.PrintstrSQL
Set rs = db.OpenRecordset(strSQL)
End Function
When you run the function, the following appears in the Watch window:
select * from orders where [employeeid]=5;
This is the correct SQL Where clause.
4. Set a Watch Expression in Visual Basic for Applications Code
A Watch expression is an one that you monitor in the Watch window You can also use Quick Watch
to see the value of an expression that has not previously been specified as a Watch expression.
You can use the Show button in the Call Stack dialog box to display the statement in one
procedure that has called the procedure listed above it.
If you choose the current procedure in the Call Stack dialog box and then click Show, the
Visual Basic Editor displays the statement at which execution was suspended.
To see the calls in the PyrNum() example above, follow these steps:
1. Add the following new procedure to the module containing PyrNum():
Public Sub ListPyrs(intMax As Integer)
Dim i As Integer
For i = 1 TointMax
Debug.Print i, PyrNum(i)
Next i
End Sub
2. Press CTRL+SHIFT+F9 to clear all breakpoints, then set a breakpoint in the Sub ListPyrs
procedure, at the following line:
For i = 1 TointMax
3. In the Immediate window, type ListPyrs 3
4. On the View menu, click Call Stack. Notice that ListPyrs is the only active procedure. Click
Close.
5. Press the function key F8 twice, to step into the function PyrNum(). Again, on the View
menu, click Call Stack.
Notice that there are now two calls listed, the most recent being PyrNum, at the top of the
stack.
6. Select the line listing ListPyrs and then click Show.
Notice that the Visual Basic Editor displays the ListPyrs procedure, and indicates the line that
calls the PyrNum() function.
The Expression column begins with the current module (for a standard module), or the current
instance of a class (for a class module). The Expression column is organized as a hierarchical tree of
information starting from the current module to display all of the module-level variables in the
current module.
The Value column shows the values of the current module objects. You can change the value of a
module-level variable in the Immediate window in order to test the behavior of your module.
The Type column shows the data type of the current module-level object.
Inspecting a selected variable's value in the Locals window can be very helpful in debugging your
module, as can changing a variable's value in the Locals window Value column to observe what
effect it has on other parts of your module.
Right click on the common dialog control and select properties from the pop up menu. you will
see a figure like the one below
Open a File
We need to use the show open method. Add the following line in the code window of the open
command button
CommonDialog1.ShowOpen
Save a File
We need to use the show save method. Add the following line in the code window of the save
command button
CommonDialog1.Showsave
Changing the color
We need to use the show changing the color method. Add the following line in the code
window of the save command button
CommonDialog1.Showcolor
Printing a document
We need to use the show print a document method. Add the following line in the code
window of the save command button
CommonDialog1.Showprinter
Program
Private Sub Command1_Click ()
CommonDialog1.DialogTitle = "select the file open"
CommonDialog1.ShowOpen
End Sub
Private Sub Command2_Click ()
CommonDialog1.DialogTitle = "Enter the Name of the file to save"
CommonDialog1.ShowSave
End Sub
Private Sub Command3_Click ()
CommonDialog1.ShowColor
Text1.ForeColor = CommonDialog1.Color
End Sub
Private Sub Command4_Click ()
CommonDialog1.ShowPrinter
End Sub
Private Sub Command5_Click ()
End
End Sub
OUTPUT
Definition
A database is a collection of information that is organized so that it can easily be accessed,
managed, and updated. In one view, databases can be classified according to types of content: full-
text, numeric, and images.
Conceptual View of
Data
Physical View
Database
Components of a database
Tables, Columns and Rows - These three items form the building blocks of a database. They store
the data that we want to save in our database.
Columns - Columns are akin to fields, that is, individual items of data that we wish to store. A
customer's name, the price of a part, the date of an invoice are all examples of columns. They are also
similar to the columns found in spreadsheets (the A, B, C etc along the top).
Rows - Rows are akin to records as they contain data of multiple columns (like the 1,2,3etc in a
spreadsheet). Unlike file records though, it is possible to extract only the columns you want to make
up a row of data. Old "records" that computers read forced the computer to read EVERYTHING,
even if you only wanted a tiny portion of the record. In databases, a row can be made up of as many
or as few columns as you want. This makes reading data much more efficient - you fetch what you
want.
Tables - A table is a logical group of columns. For example, you may have a table that stores details
of customers' names and addresses. Another table would be used to store details of parts and yet
another would be used for supplier's names and addresses.
It is the tables that make up the entire database and it is important that we do not duplicate data at all.
Only keys would duplicate (and even then, on some tables - these would be unique).
Keys - Keys are used to relate one table for another. For example. A customer places an order for
some parts. We need to store the customer's details, the parts ordered and the supplier of the parts (to
ensure we have enough stock or place a new order to restock).
Query- Queries are little programs that let the user ask questions. Things like "Give me a list of all
the customers who ordered something last month" or "List all customers in a specific area". Queries
can and often are the foundation of reports.
Depending on the database, queries can be constructed on screen or you may even be able to type in a
query command direct. Queries often use a language called "SQL" (Structured Query Language)
which is a computer language that makes accessing databases simple.
The visual Data manager option is available under the Add Ins Menu
Click on the visual data manager. Visual basic responds by showing you the Visdata windows
The menu items available are File, Utility, window and Help
There are Nine button tool. drag your mouse over the buttons and take a look at the balloon
help
From the popup menu select access. Depending upon the version of Visual basic that is
installed on your machine, you will be asked to choose the version of MDB. Select the larger
number
Choose access 2.0 if you applications is going to work on window 3.x access 7.0 is for 32 bit
platform only. VB will now present you with a Save dialog box. Enter the name of the file for
your database.
VB will display two windows, the database window and the SQL statement window. The
database windows will have an item properties click on the box with
+ to see properties that have been set or available for this database
Creating Table
Right click the mouse in the database window. From the POP-up menu select new tables. This
will result in anther window being displayed with a number of text boxes,checkboxes and a
rabbit.
After entering the table name, click on the Add Field button, you will see the Add Field
Dialog box
Name: Enter the name of the field you want to add
Orginalposition: Enter the relative position of the field
Type: enter the type of data for this field. Example interger, Text, long etc…
Validation: Message to be displayed in case the user enters invalid data for that field.
Size: Enter the size of the field
fixed Size: if selected, creates a field with a fixed sizes.
variable Length: Allows the user to modify the size of the field by dragging its borders
ValidationRule: lets you determine what data is valid in a field as it is added
DefaultValue: Enter the default value for the field
Autoincrfield: Automatically adds the next field if you are at the end of the table.
AllowZeroLength: Allows you to have a zero length string as a valid settings
Required: if the check box for this is clicked, its means that the table will not be updated if
the field is a null string.
Add: appends the current field definition to the current fields.
Close: Close the form when have finished adding fields
1. Click on the Addfield Button
1. In the textbox for name, enter empno
2. Select the type. from the dropdown list box, select integer
3. Notice that length is fixed as 2. some of the other options are made unavailable
4. Click on the required. this means that the empno cannot hold a null value
5. Now click on OK.
Double click on the table that you want to add data to.
Option information : You may have noticed a button Add Index. this button will help to build an
index for that table. the details to be provided for this functions
Name: Enter the name of the index
Indexed Fields: Select the fields used to build the index from the available fields list box that list the
field in the current table
Primary index: you can specify if the index is to be the primary index. you can have only one
primary index
Ignore Nulls: by clicking the ignore Nulls check box, you can tell the data manager not to include null
values in the index. Click OK when you are through. The new index will now get appended to the
index list.
2. Modifying tables:
Now you have created a table with some fields. there is a saying that the only thing that is
constant is change You may also want to copy the structure of a table. All this is possible with the
Visual data manager.
Modifying the name of a field: you can modify the name of a field by editing it in the table structure
dialog box. the other properties that can be modified are
Original Position
Validation rule
Default Value
Allow zero length
Required
3. Coping a Table
You can copy an entire table with the data and structure to another databases. in the database
window right click on the table that you want to copy from the pop-up menu structure Choose
‗Copy Structure‘
Visual basic allows us to manage databases created with different database programs such as
MS Access, Dbase, Paradox and etc. In this lesson, we are not dealing with how to create database
files but we will see how we can access database files in the VB environment. In the following
example, we will create a simple database application which enable one to browse customers' names.
To create this application, insert the data control into the new form. Place the data control
somewhere at the bottom of the form. Name the data control as data_navigator. To be able to use the
data control, we need to connect it to any database. We can create a database file using any database
application but I suggest we use the database files that come with VB6. Let select NWIND.MDB as
our database file.
You can also add, save and delete records using the following commands:
In the following example, you shall insert four commands and label them as First Record,
Next Record, Previous Record and Last Record.
They will be used to navigator around the database without using the data control.
You still need to retain the same data control (from example in lesson 19) but set the property
Visible to no so that users will not see the data control but use the button to browse through
the database instead.
Now, double-click on the command button and key in the codes according to the labels.
Setting Properties
Name Employee
BOFAction 0-movefirst
Caption Employee
Connect Access
DatabaseName C:\Users\AAC02\Desktop\empdetails.mdb
EOFAction 0-movelast
Recordset Type 1- Dynatest
RecordSource Employee
Datasource empno
DataField empno
Program
Private Sub Command1_Click()
employee.Recordset.AddNew
msgbox " record is added"
End Sub
Private Sub Command2_Click()
employee.UpdateRecord
msgbox " record is updated"
End Sub
Over the years, Jet has become almost synonymous with Microsoft Access, to the extent where many
people incorrectly refer to a Jet database as an "Access database".[citation needed] Even Microsoft
themselves do this sometimes, but this nomenclature should always be seen as incorrect. Jet is a
database and Access is a database application development tool (database builder).
Data integrity
Jet enforces entity integrity and referential integrity. Entity integrity is one of the key
concepts of relational databases, and ensures that no record is able to be duplicated and also
ensures that no field (or group of fields) that identify the record (the primary key) are NULL.
Thus, Jet supports primary keys. Referential integrity is where the fields that identify data that
exist in a database table (the foreign key) must correspond with an existing primary key in
that database.
If a foreign key value exists that does not have a corresponding primary key in the referenced
table, then the referential integrity is broken and the data between tables will no longer be
synchronized
Security
Access to Jet databases is done on a per user-level. The user information is kept in a separate
system database, and access is controlled on each object in the system (for instance by table or
by query).
In Jet 4, Microsoft implemented functionality that allowed database administrators to set
security via the SQL commands CREATE, ADD, ALTER, DROP USER and DROP
GROUP.
These commands were a subset of ANSI SQL 92 standard, and they also applied to the
GRANT/REVOKE commands.[1] When Jet 2 was released, security could also be set
programmatically through DAO.
Queries
Queries are the mechanisms that Jet uses to retrieve data from the database. They can be
defined in Microsoft QBE (Query By Example), through the Microsoft Access SQL Window
or through Access Basic's Data Access Objects (DAO) language.
These are then converted to an SQL SELECT statement. The query is then compiled — this
involves parsing the query (involves syntax checking and determining the columns to query in
the database table), then converted into an internal Jet query object format, which is then
tokenized and organized into a tree like structure.
In Jet 3.0 onwards these were then optimized using the Microsoft Rushmore query
optimization technology.
The query is then executed and the results passed back to the application or user who
requested the data.
The DAO Object Model
The objects in the object model are organized into various levels. You can think of these
levels as tiers in a hierarchy.
The topmost tier in the DAO object model is the JET database engine itself (DBEngine). The
second tier consists of a high-level categorization of objects.
The third, fourth and fifth tiers, etc. include a variety of different objects used to access the
functionality that the second-tier objects contain.
You traverse the tiers to find the objects you want to use.
A group of similar objects can be combined in the hierarchy as a collection. In general, the
plural names ("Databases", "Recordsets", etc.) are collections and the singular names
("Database", "Recordset", etc.) are objects with the collection.
Collection Syntax
To refer to an object in a collection, the syntax is:
CollectionName.Item("Key") -- or -- CollectionName.Item(index)
Item is the default method for all collections; therefore .Item can always be dropped from the above
syntax, reducing it to:
CollectionName("Key") -- or -- CollectionName(index)
An object's A-key is a string that uniquely identifies that object in the collection.
For example, the DeptNbr field in the collection of fields of a table could be referred to as
Fields("DeptNbr").
The index refers to the object's ordinal position in the collection, which could change if items
are added to or removed from the collection. If the DeptNbr field is the first field in the Fields
collection, it could be referred to as Fields(0).
In looking at the DAO object model, you see a good number of collections and objects. Each
of these objects has numerous methods and properties.
However, in a typical VB/DAO application, you will only need to deal with a handful of these
collections and objects.
Most likely, you will use Workspace object (indirectly), the Databaseobject, and the
Recordsets, TableDefs, and possibly QueryDefs collections.
The collections and objects used in the sample project presented in this document, along with
their properties and methods will be discussed as they are encountered, as we examine the
processing that takes place in each of the project's forms.
The DBEngine object contains and controls all other objects in the hierarchy of DAO objects.
You can't create additional DBEngine objects, and the DBEngine object isn't an element of
any collection.
A Workspace object defines a named session for a user. It contains open databases and provides
mechanisms for simultaneous transactions and, in Microsoft Access workspaces, secure
workgroup support.
A Workspace is a non-persistent object that defines how your application interacts with data by
using the Microsoft Access database engine.
Use the Workspace object to manage the current session or to start an additional session. In a
session, you can open multiple databases or connections, and manage transactions. For example,
you can:
Use the Name, UserName, and Type properties to establish a named session. The session
creates a scope in which you can open multiple databases and conduct one instance of nested
transactions.
Use the Close method to terminate a session.
Use the OpenDatabase method to open one or more existing databases on a Workspace.
Use the BeginTrans, CommitTrans, and Rollback methods to manage nested transaction
processing within a Workspace and use several Workspace objects to conduct multiple,
simultaneous, and overlapping transactions.
A Database object represents an open database.
You use the Database object and its methods and properties to manipulate an open database. In
any type of database, you can:
Use the Execute method to run an action query.
Set the Connect property to establish a connection to an ODBC data source.
Set the QueryTimeout property to limit the length of time to wait for a query to execute
against an ODBC data source.
Use the RecordsAffected property to determine how many records were changed by an action
query.
Use the OpenRecordset method to execute a select query and create a Recordset object.
Use the Version property to determine which version of a database engine created the
database.
A TableDef object represents the stored definition of a base table or a linked table (Microsoft Access
workspaces only).
You manipulate a table definition using a TableDef object and its methods and properties. For
example, you can:
Examine the field and index structure of any local, linked, or external table in a database.
Use the Connect and SourceTableName properties to set or return information about linked
tables, and use the RefreshLink method to update connections to linked tables.
Use the ValidationRule and ValidationText properties to set or return validation conditions.
Use the OpenRecordset method to create a table–, dynaset–, dynamic–, snapshot–, or
forward–only–type Recordset object, based on the table definition.
A QueryDef object is a stored definition of a query in a Microsoft Access database engine database.
You can use the QueryDef object to define a query. For example, you can:
Use the SQL property to set or return the query definition.
Use the QueryDef object's Parameters collection to set or return query parameters.
Use the Type property to return a value indicating whether the query selects records from an
existing table, makes a new table, inserts records from one table into another table, deletes
records, or updates records.
Use the MaxRecords property to limit the number of records returned from a query.
Use the ODBCTimeout property to indicate how long to wait before the query returns
records. The ODBCTimeout property applies to any query that accesses ODBC data.
Use the ReturnsRecords property to indicate that the query returns records. The
ReturnsRecords property is only valid on SQL pass-through queries.
Use the Connect property to make an SQL pass-through query to an ODC database.
A Recordset object represents the records in a base table or the records that result from running a
query.
A Container object groups similar types of Document objects together.
Each Database object has a Containers collection consisting of built-in Container objects.
Applications can define their own document types and corresponding containers (Microsoft
Access database engine databases only); however, these objects may not always be supported
through DAO.
A Relation object represents a relationship between fields in tables or queries (Microsoft Access
database engine databases only).
A Field object represents a column of data with a common data type and a common set of
properties.
Index objects specify the order of records accessed from database tables and whether or not
duplicate records are accepted, providing efficient access to data.
A Document object includes information about one instance of an object. The object can be a
database, saved table, query, or relationship (Microsoft Access database engine databases
only).
An Errors collection contains all stored Error objects, each of which pertains to a single
operation involving DAO.
Any operation involving DAO objects can generate one or more errors. As each error occurs,
one or more Error objects are placed in the Errors collection of the DBEngine object. When
another DAO operation generates an error, the Errors collection is cleared, and the new set of
Error objects is placed in the Errors collection.
The highest-numbered object in the Errors collection (DBEngine.Errors.Count - 1)
corresponds to the error reported by the Microsoft Visual Basic for Applications (VBA)
Errobje
Advantages and disadvantages of using DAO
On the plus side, DAO is fairly easy to use. And since DAO has been around longer than RDO or
ADO and has been used in more projects, it pays to know how DAO works. Furthermore, if your
application is running in a 16-bit environment, DAO is your only choice.
But DAO is older technology, and it doesn't offer as much functionality as RDO and ADO. For
instance, ADO can provide an interface to e-mail and file systems and custom business objects, as
well as other sources. Microsoft is now focusing most of its improvements and advances on ADO, as
well.
Generally, it's better to use DAO for accessing local databases where the speed is not the top priority
and the number of users is limited, and to use either RDO or ADO for accessing remote databases and
for larger scale projects.
To demonstrate how you might put DAO to work, let‘s create a simple VB project to access the data
stored in Microsoft's sample Northwind database.
1. Fire up VB and start a new project.
2. Go to Project References and select Microsoft DAO 3.6 Object Library, as shown in Figure .
(Depending on the version of VB you are using, you will have a corresponding DAO Object
Library version, so if you don't have DAO 3.6, use an earlier version instead.)
DAO object library selected in Project References
3. Add two combo boxes (cboLastNameJet and cboLastNameODBCDirect) and two command
buttons (cmdGetDataJet and cmdGetDataODBCDirect) to the form.
4. Your screen should resemble the form shown in Figure.
'close database
dbJet.Close
'close workspace
wrkJet.Close
'release objects
Set rsJet = Nothing
Set dbJet = Nothing
Set wrkJet = Nothing
End Sub
With cboLastNameODBCDirect
If rsODBCDirect.EOFAndrsODBCDirect.BOF Then
'no data - disable combo box
.Enabled = False
Else
'clear the combo box
.Clear
'move the recordset to the first row
rsODBCDirect.MoveFirst
Do Until rsODBCDirect.EOF
.AddItemTrim(rsODBCDirect("LastName"))
'move the recordset to the next row
rsODBCDirect.MoveNext
Loop
'select the first item in the combo box
.ListIndex = 0
'closerecordset
rsODBCDirect.Close
End If
End With
'close workspace
wrkODBC.Close
'release objects
Set rsODBCDirect = Nothing
Set wrkODBC = Nothing
Set conODBCDirect = Nothing
End Sub
7. Modify strLocation to reflect the location of the Northwind database on your machine or use
another .mdb database and modify Set dbJet = wrkJet.OpenDatabase(strLocation&
"Northwind.mdb") to reflect the name of the database.
8. Modify strConn to reflect the DSN name, password, and UID of a remote database.
9. Modify the query in Set rsODBCDirect = conODBCDirect.OpenRecordset("SELECT
LastName FROM Employees", dbOpenDynamic) to reflect the query you'd like to run.
10. Press [Ctrl][F5] to run the project.
11. Click the Get Data Jet button and the Get Data ODBC Direct button to obtain data using
Microsoft Jet and ODBCDirect, respectively.
You should see a screen like the one shown in FigureF.
Results of clicking a Get Data button
SSTab Control - The SSTab control provides a group of tabs, each of which acts as a container for
other controls. Only one tab is active in the control at a time, displaying the controls it contains to the
user while hiding the controls in the other tabs
An SSTab control is like the dividers in a notebook or the labels on a group of file folders. Using an
SSTab control, you can define multiple pages for the same area of a window or dialog box in your
application. Using the properties of this control, you can:
Determine the number of tabs.
Organize the tabs into more than one row.
Set the text for each tab.
Display a graphic on each tab.
Determine the style of tabs used.
Set the size of each tab.
To use this control, you must first decide how you want to organize the controls you will
place into various tabs. Set the Tabs and TabsPerRow properties to create the tabs and
organize them into rows.
Then select each tab at design time by clicking the tab. For each tab, draw the controls you
want displayed when the user selects that tab. Set the Caption, Picture, TabHeight, and
TabMaxWidth properties as needed to customize the top part of the tab.
The default Toolbox in VB doesn't include some of the most useful components. One of those that is
left out is the ssTab control ... otherwise known as the Microsoft Tabbed Dialog Control. But this
control can have hidden "gotcha's" when you use it. Here's how to avoid some of the problems.
Before you can use the ssTab control, it must be added to the Toolbox. There are several ways to do
this. One is to right-click in the body of the Toolbox and select Components ... . Another is to select
Components ... from the Project menu or press Ctrl-T. All of these will result in the Components
dialog. (An excellent example of a tabbed dialog control!)
When the ssTab control is selected, it will appear in the Toolbox just like any other VB component.
The SSTab control provides an easy way of presenting several dialogs or screens of information on a
single form using the same interface seen in many commercial Microsoft Windows applications.
The SSTab control provides a group of tabs, each of which acts as a container for other controls. Only
one tab is active in the control at a time, displaying the controls it contains to the user while hiding
the controls in the other tabs.
Figure 2.30 The SSTab control
Possible Uses
To create a Microsoft Office or Windows 95 (or later) style tabbed dialog box.
To create a custom tabbed dialog box.
Setting Tabs and Tab Rows
Before setting the number of tabs you want to add to the SSTab control, you should first decide what
your dialog box will contain and how it will be organized.
While you can set the numbers of tabs at both design time and run time, you will more than likely
find that creating your tabbed dialog at design time is much quicker and easier. You can set properties
at design time using the SSTab Property Pages which is available by right-clicking the control and
then selecting Properties.
Figure 2.31 Setting properties at design time
You set the Tab and TabsPerRow properties to define the number of tabs and rows in your
dialog box. For example, if you want to a create a tabbed dialog that contains twelve tabs you
set the Tab Count option to ‗12‘ and the TabsPerRow option to ‗4‘ — this creates a tabbed
dialog containing three rows of four tabs each. By default, the number of tabs is set at 3.
When the number of tabs and rows has been set, each tab is indexed and can then be selected
individually. For example, you can select individual tabs in the Current Tab option to change
the TabCaption property.
Tabs are indexed beginning at zero (0).
At run time, the user can navigate through the tabs by either clicking on them, by pressing
CTRL+TAB, or by using mnemonics defined in the caption of each tab.
For example, if you wanted to create a tab called ‗Print‘ and allow the user to access the tab
with the keyboard combination ALT+P, you set the TabCaption property to ‗&Print‘.
Adding Controls to Tabs
Each tab in the SSTab control is essentially a container for other controls. When you create a
tabbed dialog box, you group controls together that perform similar functions, such as printing
a document or setting display options for your application.
Once you‘ve determined how many tabs you need in your tabbed dialog box, you add
whichever controls you need to perform those functions.
To add controls to individual tab pages at design time, first select the tab by clicking on it,
then draw the controls on the tab page.
Note You should not add controls to individual tab pages using the double-click method. Double-
clicking a control from the toolbox onto a tab page places that control on every tab in the SSTab
control.
For More Information See "Containers for Controls" in "Using Visual Basic's Standard Controls"
in the Programmer’s Guide .
Enabling and Disabling Tabs at Run Time
Depending upon the functionality of your application or a particular tabbed dialog box you
create, you may want to disable some tabs in certain situations.
You use the TabEnabled property to enable and disable individual tabs. When a tab is
disabled, the text on the tab is grayed out and the user cannot select that tab. For example:
SSTab1.TabEnabled(2) = False
The TabEnabled property specifies the tab number, then disables it by setting the value to False.
Note Use the Enabled property to enable or disable the entire SSTab control.
Tab Customizing Properties
Using the SSTab control properties, you can customize the look and functionality of your tabbed
dialog box. You can set these properties at design time using the control‘s Property Pages or at run
time in code.
The Style Property
The Style property gives you two options for setting the style of your tabbed dialog box. By default,
the Style property is set to display as a Microsoft Office tabbed dialog. The tabs that appear when this
option is selected look like those in Microsoft Office for Microsoft Windows 3.1 applications. By
default, the selected tab caption text is displayed in bold.
Figure 2.32 The Microsoft Office tabbed dialog style
The second option available is the Windows 95 (or later) Property Pages tabbed dialog style. This
tabbed dialog style conforms to the user interface standards developed for Windows 95. The selected
tab caption text, unlike the Microsoft Office style, is not displayed as bold.
Figure 2.33 The Windows Property Pages tabbed dialog style
To set this property at run time use the Visual Basic constants ssStyleTabbedDialog or
ssStylePropertyPage to specify either style.
The TabOrientation Property
The TabOrientation property allows you to locate the tabs of your tabbed dialog box on either of the
four sides (top, bottom, left, right). For example:
Figure 2.34 Tab orientation set to left
When you set the orientation of the tabs to something other than top or bottom, you must also
change the font style of the tabs. Setting the tabs to left or right rotates the text vertically and
only TrueType® fonts display vertically in the SSTab control.
Change the font style using the Font property or by selecting the Font tab in the control‘s
Property Pages. Arial is a common substitute for the Windows default sans serif font.
You can set this property at run time using the following Visual Basic constants:
ssTabOrientationTop, ssTabOrientationBottom, ssTabOrientationLeft, and
ssTabOrientationRight.
The Picture Property
You can add pictures (bitmaps, icons, or metafiles) to any or all of the tabs in the SSTab control. For
example:
Figure 2.35 Adding a picture to a tab
At design time, you set the Picture property for a tab by clicking that tab and then setting the
property in the Properties window. At run time, you can set the Picture property using the
LoadPicture function or the Picture property of another control or of a Form object.
Note When setting the Picture property at design time, the graphic is saved and loaded with the
Form object containing the SSTab control. If you create an executable file, the file contains the
image. When you load a graphic at run time, the graphic isn't saved with the application.
Setting the Picture property affects the value of the TabPicture property for the current tab as well as
displays the picture in the active tab.
Adjusting Tab Height and Width
Depending upon its size, you may need to resize the tab height to accommodate the image.
Use the TabMaxHeight property to adjust the height of the tabs.
The TabMaxHeight property sets the height for every tab in the control — individual tabs
cannot be adjusted separately.
If you‘re using the Microsoft Office style tabbed dialog, you may also need to set the
TabMaxWidth property to allow both the image and the text to fit on the tab.
If you‘re using the Windows 95 style tabbed dialog, the TabMaxWidth property is ignored
and the width of each tab adjusts to the combined width of the image and the length of the text
in its caption.
Setting the WordWrap Property
When using the Microsoft Office style tabbed dialog, you may specify the exact width of the
tabs using the TabMaxWidth property.
Having done so, you can then allow tab captions to wrap to the next line, if necessary, by
setting the WordWrap property to True.
Although caption text will wrap, you are still limited by the height and width of the tabs. In
other words, you may still get clipped or hidden caption text if the height and width are
insufficient.
The Windows 95–style tabbed dialog sets tab width based on the length of the caption text;
the TabMaxWidth and WordWrap property settings are ignored.
Completing Your Custom Tabbed Dialog Box
Once you‘ve completed adding controls to each tab, you can finish designing your custom
tabbed dialog box to resemble a standard tabbed dialog box.
For example, if you want it to display like a standard Windows 95 (or later) Property Pages
dialog box, follow these steps:
Resize the underlying form so that the SSTab control is centered and equal amounts of space
remain on the top, right and left edges. Leave a larger amount of space below the control.
Add two command buttons — an OK and a Cancel button. Align them below the right edge of
the SSTab control.
Set the form‘s BorderStyle property to Fixed Dialog.
Click the Add button. The Create New Data Source dialog box will appear. Select
Microsoft Access Driver (*.mdb) from the list and click the Finish button.
The ODBC Microsoft Access Setup dialog box will appear. For Data Source Name, type
Biblio. If desired, you can type an entry for Description, but this is not required.
Click the Select button. The Select Database dialog box appears. On a default installation of
VB6 or Visual Studio 6, the BIBLIO.MDB sample database should reside in the folder
C:\Program Files\Microsoft Visual Studio\VB98. Navigate to that folder, select BIBLIO.MDB
from the file list, and click OK.
When you are returned to the ODBC Microsoft Access Setup screen, the database you
selected should be reflected as shown below. Click OK to dismiss this screen.
When you are returned to the ODBC Data Source Administrator screen, the new DSN should
appear as shown below. Click OK to dismiss this screen.
At this point, the Biblio database is ready to be used with RDO in the sample application.
Using the ADO Data Control (ADODC)
To build the first sample application, follow the steps below.
Start a new VB project, and from the Components dialog box (invoked from the Project ->
Components menu), select Microsoft ADO Data Control 6.0 (SPx) as shown below and click
OK.
The ADO Data Control should appear in your toolbox as shown below:
Put an ADO Data Control on your form, and set the properties as follows:
Property Value
Name adoBiblio
DataSourceName Biblio
SQL select * from authors
Now put three text boxes on the form, and set their Name, DataSource, and DataField
properties as follows:
Name DataSource DataField
txtAuthor adoBiblio Author
txtAuID adoBiblio Au_ID
txtYearBorn adoBiblio Year Born
UNIT-V
Crystal Reports
'Crystal Reports' is a popular third party package that is included with Visual Basic,
which allows you to create reports for your application.
The package consists of a designer - where you can design and test the reports, Crystal
Reports API calls and Crystal Reports control.
Installing Crystal Reports 4.6
Crystal Reports 4.6 is bundled with Visual Studio/Visual Basic 6.0, but it is not installed
automatically.
To install it manually, locate the CRYSREPT folder on your installation CD â€― for Visual
Studio 6.0, the path is COMMON\TOOLS\VB\CRYSREPT on the third CD.
In that folder, double-click the file CRYSTL32.EXE. You will be asked if you want to install
Crystal Reports. Respond Yes.
It will then tell you where it is going to install CR; you can override the location if desired.
Following that, CR will be installed, and a few moments later you should get a message
indicating that installation was successful.
The Sample Database
The sample database used for this tutorial (as well as others to follow) is an Access 97 format
database named EMPLOYEE.MDB.
EMPLOYEE.MDB contains three tables: EmpMast, DeptMast, and JobMast. The tables are
structured as follows: EmpMast table:
Field Name DataType Comments
EmpNbr AutoNumber Primary Key. Uniquely identifies each
employee in the database.
EmpFirst Text (50) Employee's first name
EmpLast Text (50) Employee's last name
DeptNbr Number (Long Integer) Foreign Key to PK of DeptMast table.
Identifies which department the employee
works in.
JobNbr Number (Long Integer) Foreign Key to PK of JobMast table.
Identifies the employee's job.
HireDate Date/Time Date the employee was hired
HrlyRate Number (Single) Employee's hourly rate
SchedHrs Number (Single) The number of hours per week the
employee is scheduled to work.
DeptMast table:
Field Name DataType Comments
The Create New Report dialog box appears. Click the Standard button.
The Create Report Expert dialog box appears with the Step 1: Tables tab open. Click the Data
File button:
The Choose Database File dialog box appears. Navigate to the directory where your database file
resides, then click the name of the database file so that it appears under "File Name:". Click the Add
button, then click the Done button.
The 2: Links tab then appears, showing you a diagram similar to that of Access' Relationships
diagram.
Move on by clicking the 3: Fields tab.
The "3: Fields" tab initially looks like this:
Using the "Add ->" button, select the desired fields from the "Database Fields" listbox so that they
appear in the "Report Fields" listbox. Select the fields based on the initial design. For fields that are
involved in a primary key â€― foreign key relationship, only select one of those fields from either
table (for example, select the DeptNbr field from either the DeptMast table OR the EmpMast table,
but not both).
Select the following Database Fields:
Select DeptNbr and DeptName from the DeptMast table.
Select EmpNbr From the EmpMast table.
Skip down to the JobMast table and select the JobNbr and JobTitle.
Jump back up to the EmpMast table and select the HireDate, HrlyRate, and SchedHrs.
The "Edit Formula" dialog box appears. In the "Formula text" area, type:
TrimRight ({EmpMast.EmpLast}) + ", " + TrimRight ({EmpMast.EmpFirst})
Your screen should look like this:
Note: Crystal Reports has its own formula syntax, which differs from the syntax of VB and Access
expressions. You can scroll the "Fields", "Functions", and "Operators" listboxes above the Formula
text entry area to see what's available. Also, instead of typing everything directly into the text entry
area, you can double-click on a listbox selection and the text of that selection will appear in the
Formula text box.
Click the Check button. If you entered the formula correctly, the message "No errors found" will pop
up. Passing that, click the Accept button.
The formula will then appear in the Database Fields listbox (as "@EmpName"). With @EmpName
highlighted, click the "Add->" button to add it to the Report Fields list. In the Report Fields list, drag
and drop "@EmpName" so that it appears under "EmpMast.EmpNbr". Give @EmpName a column
heading of "Employee Name".
Now we must create the annual salary formula. To do so, follow these steps:
Make sure anything OTHER than @EmpName is selected in the Database Fields listbox.
Click the Formula button.
In the "New Formula" dialog box, type "AnnSal" and click OK.
In the "Edit Formula" dialog box, type
o {EmpMast.HrlyRate} * {EmpMast.SchedHrs} * 52
click Check, then Accept.
Use the "Add->" button to bring @AnnSal over from the Database Fields list to the Report
Fields list.
In the Report Fields listbox, drag and drop the @AnnSal formula so that it is the last field in
the list.
Give @AnnSal a column heading of "Ann Salary".
Click the 4: Sort tab. Select DeptMast.DeptNbr from the "Report Fields" list and click the "Add->"
button. DeptMast.DeptNbr then appears in the "Group Fields" list. Repeat this process for
@EmpName. Your screen should look like this:
Click the 5: Total tab. Within this Total tab, an inner tabbed dialog appears, with one tab for each
field selected in the sort. On the "DeptMast.DeptNbr" tab, remove all items except "@AnnSal" from
the Total Fields list, as shown below. What we are saying is that we want to print a subtotal for the
annual salary every time there is a change, or break, in the department number.
Still in the "5: Total" tab, click the "@EmpName" tab and remove all items from the Total Fields list,
as shown below. (We don't want to print subtotals after every employee name.)
We don't need to do anything in tab 6, so click the 7: Style tab. For the title, type "Annual Salary
Expenses by Department".
Click the Preview Report button. At this time, the "Create Report Expert" is finished and you can't
go back to it, but you can make any desired changes in the Crystal Reports interface. Following is the
screen that is initially displayed after you click the Preview Report button from Step 7 of the Expert:
On the Crystal Reports toolbar, click the Zoom button, so you can see what the Expert did for you (it
gives you a start, but it needs some work):
Click the Design tab:
Still in the Page Header area, remove the column headings for Dept # and Dept Name. (Do
this by selecting each item with the mouse and pressing the Delete key.)
In the first area labeled #1: DeptNbr – A (the one above Details), select the item there and
delete it.
In the Details area, select the DeptNbr and DeptName fields, and drag them with the mouse
to the first #1: DeptNbr -A area.
Once in the new area, select these two fields and click the Bold button. Insert a text field in
this area (using the same technique as you did with "Run Date:") with the text "Department:".
Make this text field bold as well. Arrange the fields so that they look like the following (you
can resize a field by selecting it and dragging on the handles, just like resizing a control on a
VB form):
Note that the default format for the department number contains a comma. We don't want
that. Right click the department number, and select Change Format … from the context
menu.
The Format Number dialog appears, as shown below. Clear the "Thousands Separator"
checkbox and click OK. (Note: You can also add or remove comma formatting by selecting
the field and clicking the comma button on the formatting toolbar.)
Remove the commas from the formats for the employee number and the job number. Resize
the fields on the detail line and resize their corresponding column headings so that the column
headings can be fully read and the field data is lined up beneath them.
Use the screen shot below as a guide:
In the second area labeled #1: DeptNbr – A (the one below Details), you will see a text
item (denoted by X's) on the far left of the line.
Delete that text item. In the same area, toward the right-hand side of the line, you will see a
numeric item (denoted by "55.56").
This is the department subtotal. Resize this item to make it larger, and move it to the right so
that it lines up with the detail annual salary field, as shown below:
Insert a text field with the text "Subtotal for Department" to the left of the subtotal (not to the
immediate left, because we are going to insert another field between these two).
Click the Bold button to make it bold.
On the Insert menu, select Database Field … The "Insert Database Field" dialog box comes
up (shown below).
From it, select DeptNbr and drag the DeptNbr field to the subtotal line, between the text
"Subtotal for Department" and the numeric subtotal.
The second area labeled #1: DeptNbr – A should now look like this:
In the area of the report labeled Grand Total, delete all fields except the first one (a text
item with the text "Grand Total") and the last one (a numeric item that is the grand total of the
annual salaries). Resize and line up the remaining two items so that the report looks like the
following:
In the Page Footer area of the report, there is a field for the page number. With your mouse,
move this field up to the right-hand side of the page heading area.
Add a text field that says "Page:" and place it adjacent to the page number, as in the following
screen-shot:
That's just about it. Click the Preview tab to check out the finished product.
Due to the fact this was set up to print in landscape orientation, a few screen shots are presented to
show the final report. Below is the left-hand side of the report:
9. In the second #1: JobNbr – A area, delete the department number field. Replace it with the job
number field. To do this, go to the Insert menu, select Database field, and select JobNbr.
Resize the JobNbr field so that its small enough to fit where the department number used to
be. Remove the commas from the formatting and make it bold. Edit the text field "Subtotal for
Department", changing the word "Department" to "Job". Make cosmetic adjustments as
necessary.
10. That's just about it. Click the Preview tab to view the fruits of your labor. If you wish, go back
and make any adjustments you deem necessary and print out the report. When you are done,
save the report and exit Crystal Reports.
How to Print a Crystal Report from a VB Program
First, you must add the Crystal Report control to your VB toolbox. To do so, go to
Components and check Crystal Report Control 4.6 from the Components dialog box, as shown
below:
The Crystal Reports control will then appear in the VB toolbox (it is circled in the screen shot below):
The form used in the demo application associated with this topic, named frmCRDemo, is
shown below. The form contains two sets of option button control arrays (each contain two
option buttons indexed 0 and 1).
The first option button control array, named optReport, appears in the frame labelled "Select
Report"; the second option button control array, named optDestination, appears in the frame
labelled "Select Destination".
The Crystal Report control was renamed rptAnnSalExp. No other properties of the Crystal
Report control were set at design-time; all necessary properties are set in code at run-time.
Only one Crystal Report control is necessary to print any number of reports off of a form.
The Crystal Report control is not visible at run-time. Finally, there are two command buttons
on the form; the OK button and the Exit button.
The OK button runs the report based on the options selected by the user in the frames above;
the Exit button ends the application.
Following is the code for both the frmCRDemo form and a standard module called
modCommon.
The Crystal Reports-related code will be explained following the code listings.
Code for frmDemo:
Option Explicit
'------------------------------------------------------------------------
Private Sub Form_Load()
'------------------------------------------------------------------------
CenterForm Me
End Sub
'------------------------------------------------------------------------
Private Sub cmdOK_Click()
'------------------------------------------------------------------------
cmdOK_Click_Error:
End Sub
'------------------------------------------------------------------------
Private Sub cmdExit_Click()
'------------------------------------------------------------------------
Unload Me
End Sub
Option Explicit
'------------------------------------------------------------------------
Public Sub CenterForm(pobjForm As Form)
'------------------------------------------------------------------------
With pobjForm
.Top = (Screen.Height - .Height) / 2
.Left = (Screen.Width - .Width) / 2
End With
End Sub
'------------------------------------------------------------------------
Public Function GetAppPath() As String
'------------------------------------------------------------------------
End Function
Note that in the cmdOK_Click event procedure, the variable strReportName is set to
"SALDEPT.RPT" or "SALJOB.RPT", depending on which optReport button was clicked.
The variable intDestination is set to either crptToWindow or crptToPrinter, both built-in
Crystal Reports constants, depending on which optDestination button was clicked (if you
choose to send the report to a window, a "print preview" type screen appears allowing the user
to view the report on screen; if you choose to send the report to the printer, it will be sent
directly to the default printer with no preview).
The sample app references the following properties of the Crystal Report control:
ReportFileName refers to the name of the report definition that you saved in Crystal
Reports. Alternatively, this property can also be set at design-time.
DataFiles is a Crystal Reports property array specifying the database file(s) to be used as the
basis for the report.
The file you specify here will override the database file used when the report was created in
Crystal Reports. Although different MDB files can be used (at Crystal Reports design-time vs.
VB run-time), they still must contain the same table and/or query names, with the same structure,
that were used to build the report.
Destination refers to where you want to direct the output of the report. In code, you can use a
predefined constant (like crptToPrinter) or its numeric equivalent as used in the sample code.
This property can also be set at design-time.
The sample app uses either crptToWindow (numeric value of 0) or crptToPrinter (numeric
value of 1).
Action is the property that triggers the running of the report. It must be set to 1 to run.
Compiling your Visual Basic Program
Once your have completed a VB program, you can compile the program to run as a
standalone windows application, without having to launch the Visual Basic IDE.
However, before you compile your program, you have to debug your program to make
sure it is errors free.
Once the program is compiled into an EXE file (executable file), you can not debug it
anymore.
If you wish to do so, you have to correct the errors and recompile it.
To start compiling your program, click on the menu File and select Make Project1.exe, as
show in Figure 36.1.
When you click on Make Project1.exe , the Make Project dialog box will appear, as shown in
Figure 36.2.
In this dialog box, you can select the project you wish to compile. In this example, the project
I chose to compile is reversi. The option button in this dialog box let you customize the
program you are going to compile.
For example, you can enter the title of the program , the program's version and your company
name. Clicking on the compile tab will let you decide the kind of code you wish to compile.
The default option is native code and it is the best option because it normally runs faster.
It requires fewer files to run, particular the VB DLL files.
Once you have done that, you can click the OK button to compile the program. Now you
program can run as a standalone application.
You can start your program without launching the Visual Basic IDE.
Figure 36.1
Figure 36.2
Figure 36.3
Figure 36.4
Distributing Your Programs
After successfully created a VB program, you might want to market your product, either
online or offline. This means that you need to create a package that can be distributed to your
potential customers.
The package created can be distributed using CD ROM, diskette or the Internet.
The package will allow the user to install the program to install in the computer with the
standard setup routine.
To create the distributable package, you can use the Package and Development Wizard that
came with Visual Basic 6.
The main purpose of this wizard is to create a setup program that can be used to install the
application. Off course, it also does many other jobs like compiling your application and
compresses the files for easy distribution.
When you start the Package and Development Wizard, you will be presented with the following
dialog box:
First of all, you need to select the project you want to package. Here I have selected the
starwar.vbp project. Next, you need to select one of the three options.
Here, I suggest you select the first option to let the wizard create the installation package for
you to distribute it using CD ROM or the Internet.
Once you click the package option, you will see the following dialog box where you are asked
to choose a packaging script:
After you click next, you will see the following dialog box where you will be asked to choose a
packaging type. Normally we choose the Standard Setup Package.
The next dialog box that shows up will ask you where to store the package, as shown below:
The next dialog box will show you the files that will be included in the package.
When you click the Finish button, the package will be created and ready for distribution.
DATA REPORTS
Steps in building your report in Visual Basic 6
Visual Basic 6 provides you with a data report designer to create your report, it is somewhat
similar to data report designer in Microsoft Access.
The data report designer has its own set of controls which allow you to customize your report
seamlessly. The steps in creating the report in VB6 are listed below:
Step 1: Adding Data Report
Start Visual Basic as a Standard EXE project. From the Project menu in the VBE, select Add
Data Report in the dropdown menu.
Now, you will be presented with the data report environment, as shown in Figure 40.1.
The data report environment contains six controls, they are RptTextBox, RptLine,
RptFunction, RptLabel, RptImage and RptShape.
You can customize your report here by adding a title to the page header using the report label
RptLabel.
Simply drag and draw the RptLabel control on the data report designer window and use the
Caption property to change the text that should be displayed.
You can also add graphics to the report using the RptImage control.
Step 2: Connecting the report to database using Data Environment Designer
Click the Project menu, then select Data Environment. from the drop-down menu. The default data
environment will appear, as shown in figure 40.2
Figure 40.2: Data Environment
Now, to connect to the database, right-click connection1 and select Microsoft Jet 3.51 OLE DB
Provider (as we are using MS Access database) from the Data Link Properties dialog (as shown in
Figure 40.3), then click next.
Figure 40.3
Now, you need to connect to the database by selecting a database file from your hard disk. For
demonstration purpose, we will use the database BIBLIO.MDB that comes with Visual
Basic, as shown in Figure 40.4. The path to this database file is C:\Program Files\Microsoft
Visual Studio\VB98\BIBLIO.MDB.
This path varies from computers to computers, depending on where you install the file. After
selecting the file, you need to test the connection by clicking the Test Connection button at the
right bottom of the Data Link Properties dialog.
If the connection is successful, a message that says 'Test Connection Succeeded' will appear.
Click the OK button on the message box to return to the data environment.
Now you can rename connection1 to any name you like by right-clicking it. For example, you
can change it to MyConnection.
You may also change the name of DataEnvironment1 to MyDataEnvironment using the
Properties window.
Figure 40.4
The Final step is to set MydataReport as the Startup form from the Project menu, then run the
program. You will see your report as shown in Figure 40.8. You can print out your report.
Figure 40.8: The Final Report.
What is ActiveX?
What Is an ActiveX Control?
An ActiveX control is an OLE control that supports additional ActiveX features.
This section reviews the architecture of an OLE control and then describes those additional
ActiveX features (such as safety, run-time licensing, digital certificates, packaging the control,
and so on).
Description of an OLE Control
At a minimum, an OLE control is a COM object that supports the IUnknown and
IClassFactory (or IClassFactory2) interfaces.
As stated, support for these interfaces is the minimal requirement for an OLE control;
however, in order to do any meaningful work, an OLE control also supports a number of other
interfaces that provide features such as writing persistent data to disk, supporting automation
(methods, events, and properties), and supporting a user interface for the control.
Why Is It Important?
ActiveX makes it fast and easy for developers and Web producers to create unique, interactive
Web sites that will make the Internet fundamentally more useful and productive.
Web producers don't have to start from scratch and build all the parts of their interactive Web
site by hand, because there are already more than 1,000 reusable controls available in the
market.
And because ActiveX can be used with a wide variety of programming languages from
dozens of vendors, developers and Webmasters can make use of their current expertise to
more quickly create compelling content.
They can also accommodate a wide range of users, as ActiveX will be supported on multiple
operating system platforms
Description of an ActiveX Control
An ActiveX control is an OLE control that supports several additional features. These features
include:
Initialization security
Scripting security
Run-time licensing
Reduced footprint (for quick downloading)
Digital certification
Introduction
The Visual Basic® 5.0 Control Creation Edition makes creating ActiveX™ controls as easy
as creating typical Visual Basic applications.
After reading this article, you'll see just how easy it can be.
This document is designed to give you an overview of the simple process of creating ActiveX
controls with Visual Basic. If you are already familiar with any version of Visual Basic, you
should be able to create your first ActiveX control in 10 minutes!
The directions that follow will guide you through the process of building what is commonly
called a "spinner" control. A spinner control is a graphical ActiveX control that allows the
user to increase or decrease a value by using a mouse instead of a keyboard. A spinner control
is pictured below.
Figure 1. A spinner control
Now that you have an idea of what you will be building, let's get started.
Step 1: Create a Test Container
Start the Control Creation Edition, highlight Standard EXE, and click Open as shown below. This
creates the host application. This host will be used as the test container for the spinner control.