Unit I VB 6.0 Notes
Unit I VB 6.0 Notes
VB is imitated by using the Start All Programs MS Visual Studio MS Visual Basic
6.0. By Clicking the VB 6.0 icon in Desktop it can be opened. Below Figure shows the interface screen of
VB 6.0 with Menu bar, Toolbar and etc.
Toolbox
Toolbox contains a set of controls that are used to place on a form at design time thereby creating
the user interface area. Additional controls can be included in the toolbox by using the Components menu
item on the Project menu. A toolbar is shown in the below.
Pointer PictureBox
Label Textbox
Frame CommandButton
CheckBox Option Button
ComboBox List Box
Hscroll Bar VScrollBar
Timer Drive ListBox
DirListBox FileListBox
Shape Line
Image Data
OLE
The pointer helps to move and resize the controls and Forms
Label displays a text that the user cannot modify or interact with.
Frame control serves as a visual and functional container for controls.
CheckBox displays a True/False or Yes/No option.
TextBox is a control used to display message and enter text.
The ListBox displays a list of items from which a user can select one.
ComboBox contains a TextBox and a ListBox. This allows the user to select an item from the
dropdown ListBox or to type a selection in the TextBox.
HScrollBar or VScrollBar controls allow the user to select a value within the specified range of values.
Timer control executes timer events at specified intervals of time.
DirListBox allows the user to select directories and paths, which are displayed.
Shape control adds a shape to a Form.
Image control is used to display icons, bitmaps, metafiles, etc.
OLE control is used to link or embed an object, display and manipulate data from other Windows
based applications
PictureBox displays icons/bitmaps and metafiles. It display text or acts as a visual container for other
controls.
CommandButton carries out the specified action when the user chooses it.
The OptionButton control which is a part of an option group allows the user to select one option even
if it displays multiple choices.
The DriveListBox displays the valid disk drives and allows the user to select one of them.
The FileListBox displays a set of files from which a user can select the desired one.
Line controls draws a straight line to the Form.
Data control enables the user to connect to an existing database and display information from it.
Form serves as a window that can be customized and controls, graphics and pictures can also be
added to it.
Project Explorer
The project explorer serves as a quick reference to the various elements of a project namely form,
classes and modules. All of the objects that make up the application are packed in a project. A typically
project contains one form, which is a window that is designed as part of the program’s interface.
Properties Window
The Properties window exposes the various characteristics of selected objects. Each and every
Form in an application is considered an object. All the characteristics of an object are called its properties.
Object Browser
The object Browser allows browsing through the various properties, events and methods that are
made available to us. It is accessed by selecting Object Browser from the View menu or by pressing F2.
properties such as Enabled, Font, Multi Line, Text, Visible, etc. A method is an action that can be
perfomed on objects. The TextBox has associated with Refresh, SetFocus etc.
VB programs are built around Events. Events are various things that can happen in a program. In
an event driven application, the program statements are executed only when calls a specific part of the
code that is assigned to the events.
Border Style
Forms can have a variety of types of borders. Various borders that are available in VB are Name,
Fixed Single, Sizeable, Fixed Double, Fixed ToolWindow and Sizeable ToolWindow.
Caption
The title for the window is stored in the Caption property, the caption appears below the form’s
icon when the form is minimized.
Control Box
This property determines whether the Control box, available by clicking the upper left corner of a
window, will be shown or not.
Icon
This property specifies the icon for the window in the upper left corner of the window.
MousePointer
This property sets the value that indicates the type of mouse pointer displayed when the mouse
pointer appears over a particular area of the object at runtime.
MaxButton
This property indicates Whether the Maximize button should be shown and the Maximize choice
made available in the Control Box menu.
MDIChild
This property specifies if this window must be shown within a multiple document interface (MDI)
window.
MinButton
This property indicates whether the Minimize button should be shown and the Minimize choice
made available in the Control Box menu.
Moveable
By setting it to False, it is possible to prevent the user from moving the window manually. This is
useful for splash screens and other informational dialog boxes that are shown and dismissed quickly.
StartUpPosition
Instead of writing code to position user window, user can pick a starting position from this drop-
down menu. The available choices are Manual, CenterOwner, CenterScreen and Windows Default.
WindowState
This property indicates whether the window is shown normally, maximized or minimized. It is
possible to pick a starting state for your Form at design time so that when you show the window, it comes
up in that state.
Show Method
The Show method is used to display the Form object. For example, to display the form
frmCalculator, the following code is written.
FrmCalculator.Show
A New Standard EXE Project item is selected from the File menu that displays a New Project
dialog box. The standard EXE is chosen for normal applications. Visual Basic responds by displaying the
Project and Form windows. Though no change have made to the Form, it is better to save the project at
the early stage of the design. When a project is saved, two files are saved, namely Project file and Form
file. The project file has .VBP extension and its contains information that VB uses for building the
project. The Form file contains information about from and has .FRM extension. The Save Project
command is selected from the File Menu. VB responds by displaying a Save File As dialog box. A file
name called Display.frm is given and Save button has to be clicked on. VB than display a Save Project As
dialog box. The project file is saved as Display.vbp.
Code editor window includes List Properties/Methods which presents a list of properties available
for controls.
The application is run by clicking Start command form the Run menu or Pressing F5. When the
Display button is clicked the message Visual Basic 6 is displayed in the TextBox. Clicking the Clear
button clears the message, while button terminates the application.
Ending an Application
The End statement is used to terminate the execution of the application. It unloads all the forms
from memory.
Class modules (.CLS filename extension) are the foundation of object oriented programming in VB.
New objects can be created by writing code in class modules. Each module can contain:
Declaration
May include constant, type, variable and DLL procedure declarations.
Procedure
A sub function or property procedure that contains piece of code that can be executed as a unit
Data Types
By default Visual Basic variables are of the variant data type. The variant data type can store
numeric, date/time or string data. When a variable is declared, a data type is supplied for it that
determines the kind of data of data it can store. The fundamentals data types in VB including variant are
integer, long, single, double, string, currency, byte and Boolean. VB supports a vast array of data types.
Each data type has limits to the kind of information and minimum and maximum values it can hold.
Variables
Variables are used for storing values temporarily. A defined naming strategy has to be followed
while naming a variable. A variable name must begin with an alphabet letter and should not exceed 255
characters. It must be unique within the same scope. It should not contain any special characters such as
%, &, #, etc. There are ways of declaring variable in VB. Depending on where variable are declared and
how they are declared, user can determine how they can be used in the application. The different types of
declaring variables in VB are discussed below
Explicit Declaration
Declaring a Variable tells Visual Basic to reserve space in memory. It is not a must that a variable
should be declared before using it. Automatically whenever Visual Basic encounters a new variable, it
assigns the default variable type and value. This is called implicit declaration.
Though this type of declaration is easier for the user, it is advisable to declare them explicitly. The
variables are declared with a Dim statement to name the variable and its type. The As type clause in the
Dim statement allows to define the data type or object type of the variable. This is called explicit
declaration.
Syntax
Dim variable [As type]
Example
Dim strname As String
Dim intCounter As Integer
Scope of Variables
A scope of variable to a procedure-level (local) or module-level variable depending on how it is
declared. The scope of variable, procedure or object determines which parts of the code in the application
are aware of the variable’s existence.
A variable is declared is general declaration section of a Form and hence is available to all the
procedure. Local variables are recognized only in the procedure in which they are declared. They can be
declared with Dim and Static keywords. If we want a variable to be available to all the procedures within
the same module or to all the procedures in an application, a variable is declared with border scope.
Local Variables
A local variable is one that is declared inside a procedure. This variable is only available to the
code inside the procedure and can be declared using the Dim statement
Dim intTemp As Integer
The local variables exist as long as the procedure in which they are declared, is executing. Once a
procedure is executed the value of its local variables are lost and memory used by these variables is freed
and can be reclaimed. Variables that are declared with keyword Dim exist only as long as the procedure is
being executed.
Static Variables
Static variables are not re-initialized each time Visual Basic invoke a procedure and thus retains or
preserves value even when a procedure ends. In case we need to keep track of the number of times a
CommandButton in an application is clicked, a static counter variable has to be declared. These static
variables are also ideal for making controls alternatively visible or invisible. A static variable is declared
as given below.
Static intPermanent As Integer
Variables have a lifetime in addition to scope. The values in module-level and public variables are
preserved for the lifetime of an application whereas local variables declared with Dim exist only while the
procedure in which they are declared is still being executed. The value of a local variable can be
preserved using the Static keyword. The following procedure calculates the running total by adding new
values to the previous variable value.
Function RunningTotal()
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function
If the variable Accumulated was declared with Dim instead of Static, the previously accumulated values
would not be preserved across calls to the procedure and the procedure would return the same value with
which it was called. To make all variables in a procedure static, the Static keyword is placed at the
beginning of the heading in the statement below.
Static Function RunningTotal()
code. For example, if the public integer variable intY is declared in both Forml and Modulel of a project
it can be referred as Fonnl.intY and Module1.intY.
Public vs Local Variables. A variable can have the same name and different scope. For example, we can
have a public variable named R and within a procedure we can declare a local variable R. References to
the name R within the procedure would access local variable and references to R outside the procedure
would access the public variable.
Sub Procedures
A sub procedure can be placed in standard, class and form module. 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 | Pub1ic] [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-general procedures and event procedures.
Event Procedures
An event procedure is a procedure block that contains the control’s name, an under score( _ ), and
the event name. The following syntax represents the event procedure for a Form_Load event.
Private Sub Form_Load( )
… Statement block …
End Sub
Event Procedures acquire the declaration as Private by default.
General Procedures
A general procedure is declared when several event procedures perform the same actions. It is a
good programming practice to write common statement m a separate procedure (general procedure) and
then call them in the event procedure. In order to add a general procedure following steps are followed.
The Code window is opened for the module to which the procedure is to be added.
The Add Procedure option is chosen from the Tools menu, which opens as Add Procedure dialog box
The name of the procedure is typed in the Name textbox.
Under Type, Sub is selected to create a Sub procedure, Function to create a Function procedure or
Property to create a Property procedure.
Under Scope, Public is selected to create a procedure that can be invoked the module or Private to
create a procedure that can be invoked only from within the module.
We can also create a new procedure in the current module by typing Sub ProcedureName.
Function ProcedureName or Property ProcedureName in the Code window. A Function procedure returns
a value and a Sub procedure does not return a value.
Function Procedures
Functions are like sub procedures, except that 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 which are complete
within the function. The following function procedure calculates the third side or hypotenuse of a right
triangle, where A and B are the other two sides. It takes two arguments A and B (of data type Double) and
finally returns the result.
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 that sets the value of a property, Property Get procedure that returns
the value of a property and Property Set procedure that sets the reference to an object.
Control Structure
If...Then...Else Statement
The If…Then block is used for conditional execution of one or more statements.
If Condition Then
Statements
End If
The statement is executed only if the condition is true. The condition is usually a comparison, but it can
be any expression that evaluates a numeric value. If…Then-Else block is used to define several blocks of
statements, in order to execute one block. The following block of statement illustrates If...Else...End If
statements.
If A=l Then
Statements
Else
Statements
End if
The following example illustrates the If...Then ...Else statement.
Private Sub Commandl_Click()
If Val(Textl.Text) < 10 Then
MsgBox “It is a Single Digit Number"
Else lf Val(Text1.Text) < 100 Then
Select…Case Statement
Select...Case structure is an alternative to If…Then .... Elself for selectively executing a single
block of statements from among multiple blocks of statement. Select...Case is more convenient to use
than the If..Else..End If. The following program block illustrates the working of Select ... Case.
Select case Index
Case 0
Statements
Case 1
Statements
End select
Select…Case structure evaluates an expression once at the top of the structure, where as If..Then…Else If
structure evaluates different expressions for each Else If statement.
msgbox name$
Loop Until name$ = “NIL”
End Sub
At the runtime it asks for the Name and until it is entered as “NIL” the loop remains infinite.
If we want to specify the lower limit, then the parenthesis should include both the lower and upper
limit along with the To keyword. An example for this is given below.
Dim lengths(1 To 10) As Integer
In the above statement, an array of 10 elements is declared but with indexes running from 1 to 10. A
public array can be created using the keyword Public instead of Dim as shown below:
Public digits(20) As Integer
Multidimensional Arrays
A multidimensional array is used when we need to represent or store information of different
dimension. For example to hold the student registration number and marks of the student, we need to
mention its x and y co-ordinates. The following statement declares a two-dimensional 50 by 50 array
within the procedure.
Dim Marks(50,50)
It is also possible to define explicit lower limits for one or both the dimensions as for fixed size arrays.
An example for this is given here.
Dim StudMarks(101 to 200, 1 to 100)
Any number of dimensions can he declared in a multidimensional array. An example for a three
dimensional array with defined lower limits is given below.
Dim StudDetails(101 To 200,1 To 100,1 To 100)
Dynamic Array
There will be a situation when the user may not know the exact size of the array at design time.
Under such circumstances, a dynamic array can be initially declared and the user can then add elements
when needed instead of declaring the size of the array at design time.
Dim NewArray()
The actual number of elements can be allocated using a ReDim statement. This example allocates the
number of elements in the array based on the value of the variable Y.
ReDim NewArray(Y + 1)
The ReDim statement can appear only in a procedure, which is an executable statement. The same way of
declaration as used for fixed arrays is used for declaring ReDim statement also. ReDim is an executable
statement. The lower and upper limits for each dimension can also be specified explicitly as in a fixed size
array. An example for this is given below
ReDim FirstArray(4 to 12)
Each time on executing the ReDim statement, the current data stored in the array is lost and the default
value is set. But if we want to change the size of the array without losing the previous data, we have use
the preserve keyword with the ReDim statement. This is shown in the example given below.
ReDim Preserve NewArray(Ubound(FirstArray)+1)
When the Preserve keyword is used, only the upper limits of the last dimension in a multi dimensional
array can be changed. No other dimensions or the lower limit of the last dimension can be changed.
The user defined data type can be declared with a variable using the Dim statement as in any other
variable declaration statement. An array on these user-defined data types can also be declared. An
example to consolidate these two features is given below.
Dim Electronicgoods As ProductDetails ‘ One record
Dim Electronicgoods(lO) As ProductDetails ‘ An array of 11 record
A User-defined type can be referenced in an application by using the variable name in the
procedure along with the item name in the Type block. Say, for example if the text property of a textbox
namely text1 is to be assigned the name of an electronic item is written as given below.
Textl.text = Electronicgoods.prodname
If the same is implemented as an array, then the statement changes to the following.
Textl.text = Electronicgoods(i).prodname
Here i is the index of the array. User defined types can also be passed to procedures to allow many related
items as one argument.
Sub ProdData(Electronicgoods As ProductDetails)
Textl.text = Electronicgoods.prodname
Text2.text = Electronicgoods.price
End sub
Constants
Constants are named storage locations in memory, the value of which does not change during
program execution. They remain the same throughout the program execution. When the user wants to use
a value that never changes, a constant can be declared and created. The Const statement is used to create
a constant. Constants can be declared in local, form, module or global scope and can be public or private
as for variables. Constants can be declared as illustrated below.
Public Const gravityconstant As Single = 9.81
represents the time between 0:00:00 and 29:59:59 hours inclusive. The system's current date and time can
be retrieved using the Now, Date and Time functions in VB, The Now function retrieves the date and
time, While Date function retrieves only date and Time function only retrieves the time. To display both
the date and time together a message box is displayed using the statement given below.
MsgBox "The current date and time of the system is" & Now
Here ‘&’ is used as a concatenation operator to concatenate the string and the Now function. Selective
portions of the date and time value can be extracted using following functions given in the below.
Function Extracted Portion
Year() Year(Now)
Month() Month(Now)
Day() Day(Now)
WeekDay() WeekDay(Now)
Hour() Hour(Now)
Minute() Minute(Now)
Second() Second(Now)
The calculation and conversion functions related to data and time are listed below
Function Description
DateAdd( ) Returns a date to which a specific interval has been added
DateDiff( ) Returns a Long data type value specifying the interval between the two values
DatePart( ) Returns an Integer containing a specified part of a given date.
DateValue( ) Converts a string to a date.
TimeValue( ) Converts a string to a time.
DateSerial( ) Returns a date for a specified year, month and day.
DateDiff Function
The DateDiff function returns the interval between two dates in terms of years, months or days.
The syntax for this given below
DateDiff(interval, date1, date2 [,firstdayofweek[,firstdayofweek]])
Format Function
The format function accepts a numeric value and converts it to a string in the format specified by the format
argument. The syntax is given below
Format(expression[, format [,firstdayofweek[,firstdayofweek]]])
The Format function syntax with various parts are listed below
Part Expression format
Expression Required any valid expression
format Optional. A valid named or user-defined format expression
firstdayofweek Optional. A constant that specifies the first day of the week
firstweekofyear Optional. A constant that specifies the first week of the year
Logical Operators
There are six logical operators. The most common operators are And, Or and Not operators. And
Xor, Equ and Imp operators are advanced operators.
Operator Functions
And Combines two expressions. Both the expression must be True for the entire expression
to be True
Or Combines two expressions. If one of the expression is True for the entire expression is
True
Not The Negative of single expression
Xor Combines two expressions. The entire expression consider to be True if the two
expression are not both True or False
Equ Combines two expressions. Both expression must be True or False for the entire
expression to be True
Imp Combines two expretyg rssions. The entire expression is True except when first
expression is True and the second expression is False
Test Strings
VB string functions can manipulate strings in applications. Below table given brief description
about the string functions in VB.
Function Name Purpose
StrComp( ) Compare two strings
Format, Lcase( ) Converts the string to lowercase
Format, Ucase( ) Converts the string to uppercase
Space, String( ) Creates a string of repeating character
Len( ) Finds the length of a string
Format( ) Format a string
Lset( ), Rset( ) Justify a string
Instr( ) Returns a Variant(Long) specifying the position of the
first occurrence of one string within another
Left( ) Returns a Variant(String) containing a specified number
of characters from the left side of the string
Mid( ) Returns a Variant(String) containing a specified number
of characters from a string
Right( ) Returns a Variant(String) containing a specified number
of characters from the right side of the string
Trim( ) Returns a Variant (String) containing a copy of a
specified string without leading spaces and trailing
spaces.
Ltrim( ) Returns a Variant (String) containing a copy of a
specified string without leading spaces.
Rtrim( ) Returns a Variant (String) containing a copy of a
specified string without trailing spaces.
StrConv( ) Converts the strings
**********
In addition to properties and events, methods can also be used to manipulate controls from code.
For example, 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 OptionButton or CheckBox controls, ListBox
entries or ScrollBars to select a value.
Classification of Controls
Visual Basic controls are broadly classified as standard controls, ActiveX controls and insertable
objects. Standard controls such as CommandButton, Label and Frame controls are contained inside a
.EXE file and are always included in the 'l'oolbox which cannot removed. ActiveX controls exist as
separate files with .VBX or .OCX extension. They include specialized controls such as
MSChart Control
The Communicating Control
The Animation control
The List View control
An ImageList control
The Multimedia control
The Internet Transfer control
A WinSock control
The Tree View control
The Syslnfo Control
The Picture Clip control
These built-in ActiveX controls will be discussed at length in Chapter 14. Some of these objects support
OLE automation, which allow programming another application object from within Visual Basic
application.
By default, Visual Basic assigns a tab order to controls as we draw them on a form, with the
exception of the Menu, Timer. Data, Image, Line and Shape controls which are not included in the tab
order. At run time, invisible or disabled controls and controls that cannot receive the focus (Frame and
Label controls) remain in the tab but are skipped during tabbing. Setting the TabIndex property of
controls is a must in development environment.
Each new control is placed last in the tab order. If we change the value of a control's
Tablndex property to adjust the default tab order, VB automatically re-numbers the TabIndex of other
controls to reflect insertion and deletions. We can make changes at the design time using the Properties
window or at run time in code.
We can write code that changes the caption property displayed by a Label control in response to
events at run time. We can also use a Label to identify the control, such as TextBox control, that
doesn't have its own Caption property.
The AutoSize and WordWrap properties should be set if users wants the Label to properly display
variable-length lines or varying numbers of lines.
A Label control can also act as a destination in a DDEconversation. Set the LinkTopic property to
establish a link, set the LinkItem property to specify an item for the conversation, and set the
LinkMode property to activate the link. When these properties have been set, VB attempts to initiate
the conversation and displays a message if it’s unable to do so.
Set the UseMnemonic property to True if you want to define a character in the Caption property of
the Label as an access key
Example
A new Standard EXE project is opened and the Form and the project is saved as Option. frm and
Option.vbp respectively.
The Form is designed as per the following specifications table. The design Form appears as shown
below Figure.
The Val function is used to translate string to a number and can recognize Octal and
Hexadecimal strings. The LTrim function trims the leading blanks in the text. The following code is
entered in the click event of the OptionButton controls.
Private Sub optOct_Click()
Textl.Text = Oct(currentval)
Dept. of Computer Science, BCAS, Erode 23
Visual Programming – Unit I
End Sub
Private Sub optHex_Click()
Textl.Text = Hex(currentval)
End Sub
The List property sets or returns that text of an item in a list box. The index number is passed to the list
property to specify the item to be accessed. To return the text of the selected item, the ListIndex property
is passed as shown in the following example:
Str = MyList.List(MyList.ListIndex)
To return the string for a ListBox, the Text property of the control is used as shown in the following
example:
Str = cmbList1.Text
The Dropdown combo box first appears as only an edit area with a down arrow button at the right.
The list portion stays hidden until the user clicks the down-arrow button to drop down the list portion. The
user can either select a value from the list or type a value in the edit area.
The Drop-down list combo box turns the combo box into a drop-down list box. At run time, the
control looks like the drop-down combo box. The user could click the down arrow to view the list. The
difference between Dropdown combo and Drop-down list combo is that the edit area in the dropdown list
is disabled. The user can select only one of the list items and cannot type an item in the edit area. This
area, however, does display the item currently selected in the list.
Generally the ComboBox is preferred when there is a list of choices. It saves space on a Form. The
full list is not displayed until the user clicks the down arrow (except for style 1). An illustration of
different types of combo boxes is shown in below figure.
The AddItem method is used to add values to the ComboBox and ListBox. Similarly the
RemoveItem method is used to remove items from the ListBox or ComboBox. Let us now develop a
small application that uses AddItem, RemoveItem and Clear methods. The application contains a
TextBox, ListBox and three Label and CommandButton controls as shown in below figure. It is designed
in name in the TextBox. When the Add button is clicked, the types name is added in the ListBox. A
particular entry in the ListBox can be removed by selecting the item and choosing the Remove button.
Example
For the supermarket SM & Co. develop an application to Add, Remove, Clear the list of items and
then finally close the application.
Following event procedure are added for the TextBox, CommandButton and ListBox controls.
Private Sub Text1_Change()
cmdAdd.Enabled = (Len(Text1.Text) > 0)
End Sub
shown below where thumb of the ScrollBar is positioned at the centre. When the thumb’s position is
changed, it should in the TextBox.
choice = “*”
End Sub
Private Sub cmdDiv_Click()
Text1.Text = “”
preval = curval
curval = 0
choice = “/”
End Sub
To print the result on the TextBox, the following code is entered in the cmdEqual_Click( ) event
procedure.
Private Sub Command2_Click()
Select Case choice
Case "+"
result = preval + curval
Text1.Text = Str(result)
Case "-"
result = preval - curval
Text1.Text = Str(result)
Case "*"
result = preval * curval
Text1.Text = Str(result)
Case "/"
result = preval / curval
Text1.Text = Str(result)
End Select
curval = result
End Sub
Save and Run the project. On clicking digits of user ‘s choice and an operator button, the output appears
as shown below: