Getting Started With Visual Basic 6
Getting Started With Visual Basic 6
0
Visual Basic is initiated by using the Programs option > Microsoft Visual Basic 6.0 > Visual Basic 6.0.
Clicking the Visual Basic icon, we can view a copyright screen enlisting the details of the license holder of
the copy of Visual Basic 6.0. Then it opens in to a new screen as shown in figure 1 below, with the
interface elements Such as MenuBar, ToolBar, The New Project dialog box. These elements permit the
user to buid different types of Visual Basic applications.
The Integrated Development Environment
One of the most significant changes in Visual Basic 6.0 is the Integrated Development Environment (IDE).
IDE is a term commonly used in the programming world to describe the interface and environment that we
use to create our applications. It is called integrated because we can access virtually all of the
development tools that we need from one screen called an interface. The IDE is also commonly referred
to as the design environment, or the program.
Tha Visual Basic IDE is made up of a number of components
• Menu Bar
• Tool Bar
• Project Explorer
• Properties window
• Form Layout Window
• Toolbox
• Form Designer
• Object Browser
In previous versions of Visual Basic, the IDE was designed as a Single Document Interface (SDI). In a
Single Document Interface, each window is a free-floating window that is contained within a main window
and can move anywhere on the screen as long as Visual Basic is the current application. But, in Visual
Basic 6.0, the IDE is in a Multiple Document Interface (MDI) format. In this format, the windows
associated with the project will stay within a single container known as the parent. Code and form-based
windows will stay within the main container form.
Figure 1 The Visual Basic startup dialog box
Menu Bar
This Menu Bar displays the commands that are required to build an application. The main menu items
have sub menu items that can be chosen when needed. The toolbars in the menu bar provide quick
access to the commonly used commands and a button in the toolbar is clicked once to carry out the
action represented by it.
Toolbox
The Toolbox contains a set of controls that are used to place on a Form at design time thereby creating
the user interface area. Additional controls can be included in the toolbox by using the Components menu
item on the Project menu. A Toolbox is represented in figure 2 shown below.
Figure 2 Toolbox window with its controls available commonly.
Control Description
Pointer Provides a way to move and resize the controls form
Displays icons/bitmaps and metafiles. It displays text or acts as a visual
PictureBox
container for other controls.
TextBox Used to display message and enter text.
Frame Serves as a visual and functional container for controls
CommandButton Used to carry out the specified action when the user chooses it.
CheckBox Displays a True/False or Yes/No option.
OptionButton control which is a part of an option group allows the user to
OptionButton
select only one option even it displays mulitiple choices.
ListBox Displays a list of items from which a user can select one.
Contains a TextBox and a ListBox. This allows the user to select an ietm
ComboBox
from the dropdown ListBox, or to type in a selection in the TextBox.
HScrollBar and These controls allow the user to select a value within the specified range
VScrollBar of values
Timer Executes the timer events at specified intervals of time
DriveListBox Displays the valid disk drives and allows the user to select one of them.
DirListBox Allows the user to select the directories and paths, which are displayed.
FileListBox Displays a set of files from which a user can select the desired one.
Shape Used to add shape (rectangle, square or circle) to a Form
Line Used to draw straight line to the Form
used to display images such as icons, bitmaps and metafiles. But less
Image
capability than the PictureBox
Enables the use to connect to an existing database and display information
Data
from it.
Used to link or embed an object, display and manipulate data from other
OLE
windows based applications.
Label Displays a text that the user cannot modify or interact with.
Project Explorer
Docked on the right side of the screen, just under the tollbar, is the Project Explorer window. The Project
Explorer as shown in in figure servres as a quick reference to the various elements of a project namely
form, classes and modules. All of the object that make up the application are packed in a project. A
simple project will typically contain one form, which is a window that is designed as part of a program's
interface. It is possible to develop any number of forms for use in a program, although a program may
consist of a single form. In addition to forms, the Project Explorer window also lists code modules and
classes.
Figure 3 Project Explorer
Properties Window
The Properties Window is docked under the Project Explorer window. The Properties Window exposes
the various characteristics of selected objects. Each and every form in an application is considered an
object. Now, each object in Visual Basic has characteristics such as color and size. Other characteristics
affect not just the appearance of the object but the way it behaves too. All these characteristics of an
object are called its properties. Thus, a form has properties and any controls placed on it will have
propeties too. All of these properties are displayed in the Properties Window.
Object Browser
The Object Browser allows us to browse through the various properties, events and methods that are
made available to us. It is accessed by selecting Object Browser from the View menu or pressing the key
F2. The left column of the Object Browser lists the objects and classes that are available in the projects
that are opened and the controls that have been referenced in them. It is possible for us to scroll through
the list and select the object or class that we wish to inspect. After an object is picked up from the Classes
list, we can see its members (properties, methods and events) in the right column.
A property is represented by a small icon that has a hand holding a piece of paper. Methods are denoted
by little green blocks, while events are denoted by yellow lightning bolt icon.
Object naming conversions of controls (prefix)
Form -frm
Label-lbl
TextBox-txt
CommandButton-cmd
CheckBox -chk
OptionButton -opt
ComboBox -cbo
ListBox-lst
Frame-fme
PictureBox -pic
Image-img
Shape-shp
Line -lin
HScrollBar -hsb
VScrollBar –vsb
+ Add 5+5 10
- Substract 10-5 5
/ Divide 25/5 5
\ Integer Division 20\3 6
* Multiply 5*4 20
^ Exponent (power of) 3^3 27
Mod Remainder of division 20 Mod 6 2
& String concatenation "George"&" "&"Bush" "George Bush"
Relational Operators
Logical Operators
Operators Description
OR Operation will be true if either of the operands is true
AND Operation will be true only if both the operands are true
There are many ways of declaring variables in Visual Basic. Depending on where the variables are
declared and how they are declared, we can determine how they can be used by our application. The
different ways of declaring variables in Visual Basic are listed below and elucidated in this section.
• Explicit Declaration
• Using Option Explicit statement
• Scope of Variables
Explicit Declaration
Declaring a variable tells Visual Basic to reserve space in memory. It is not must that a variable should be
declared before using it. Automatically whenever Visual Basic encounters a new variable, it assigns the
default variable type and value. This is called implicit declaration. Though this type of declaration is easier
for the user, to have more control over the variables, it is advisable to declare them explicitly. The
variables are declared with a Dim statement to name the variable and its type. The As type clause in the
Dim statement allows to define the data type or object type of the variable. This is called explicit
declaration.
Syntax
Dim variable [As Type]
For example,
Dim strName As String
Dim intCounter As Integer
Scope of variables
A variable is scoped to a procedure-level (local) or module-level variable depending on how it is declared.
The scope of a variable, procedure or object determines which part of the code in our application are
aware of the variable's existence. A variable is declared in general declaration section of e Form, and
hence is available to all the procedures. Local variables are recognized only in the procedure in which
they are declared. They can be declared with Dim and Static keywords. If we want a variable to be
available to all of the procedures within the same module, or to all the procedures in an application, a
variable is declared with broader scope.
Local Variables
A local variable is one that is declared inside a procedure. This variable is only available to the code
inside the procedure and can be declared using the Dim statements as given below.
Dim sum As Integer
The local variables exist as long as the procedure in which they are declared, is executing. Once a
procedure is executed, the values of its local variables are lost and the memory used by these variables is
freed and can be reclaimed. Variables that are declared with keyword Dim exist only as long as the
procedure is being executed.
Static Variables
Static variables are not reinitialized each time Visual Invokes a procedure and therefore retains or
preserves value even when a procedure ends. In case we need to keep track of the number of times a
command button in an application is clicked, a static counter variable has to be declared. These static
variables are also ideal for making controls alternately visible or invisible. A static variable is declared as
given below.
Static intPermanent As Integer
Variables have a lifetime in addition to scope. The values in a module-level and public variables are
preserved for the lifetime of an application whereas local variables declared with Dim exist only while the
procedure in which they are declared is still being executed. The value of a local variable can be
preserved using the Static keyword. The follwoing procedure calculates the running total by adding new
values to the previous values stored in the static variable value.
Function RunningTotal ( )
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function
If the variable Accumulate was declared with Dim instead of static, the previously accumulated values
would not be preserved accross calls to the procedure, and the procedure would return the same value
with which it was called. To make all variables in a procedure static, the Static keyword is placed at the
beginning of the procedure heading as given in the below statement.
Static Function RunningTotal ( )
Example
The following is an example of an event procedure for a CommandButton that counts and displays the
number of clicks made.
Private Sub Command1_Click ( )
Static Counter As Integer
Counter = Counter = 1
Print Counter
End Sub
The first time we click the CommandButton, the Counter starts with its default value of zero. Visual Basic
then adds 1 to it and prints the result.
e.g.: Assume you have to find the grade using select...case and display in the text box
Dim average as Integer
average = txtAverage.Text
Select Case average
Case 100 To 75
txtGrade.Text ="A"
Case 74 To 65
txtGrade.Text ="B"
Case 64 To 55
txtGrade.Text ="C"
Case 54 To 45
txtGrade.Text ="S"
Case 44 To 0
txtGrade.Text ="F"
Case Else
MsgBox "Invalid average marks"
End Select
number = 1
While number <=100
number = number + 1
Wend
The above coding will display numbers vertically on the form. In order to display numbers horizontally the
following method can be used.
For x = 1 To 50
Print x & Space$ (2);
Next
To increase the space between the numbers increase the value inside the brackets after the & Space$.
Following example is a For...Next repetition structure which is with the If condition used.
Dim number As Integer
For number = 1 To 10
If number = 4 Then
Print "This is number 4"
Else
Print number
End If
Next
In the output instead of number 4 you will get the "This is number 4".
Fixed-size array : The size of array always remains the same-size doesn't change during the program
execution.
Dynamic array : The size of the array can be changed at the run time- size changes during the
program execution.
Fixed-sized Arrays
When an upper bound is specified in the declaration, a Fixed-array is created. The upper limit should
always be within the range of long data type.
Declaring a fixed-array
Dim numbers(5) As Integer
In the above illustration, numbers is the name of the array, and the number 6 included in the parentheses
is the upper limit of the array. The above declaration creates an array with 6 elements, with index
numbers running from 0 to 5.
If we want to specify the lower limit, then the parentheses should include both the lower and upper limit
along with the To keyword. An example for this is given below.
Dim numbers (1 To 6 ) As Integer
In the above statement, an array of 10 elements is declared but with indexes running from 1 to 6.
A public array can be declared using the keyword Public instead of Dim as shown below.
Public numbers(5) As Integer
Multidimensional Arrays
Arrays can have multiple dimensions. A common use of multidimensional arrays is to represent tables of
values consisting of information arranged in rows and columns. To identify a particular table element, we
must specify two indexes: The first (by convention) identifies the element's row and the second (by
convention) identifies the element's column.
Tables or arrays that require two indexes to identify a particular element are called two dimensional
arrays. Note that multidimensional arrays can have more than two dimensions. Visual Basic supports at
least 60 array dimensions, but most people will need to use more than two or three dimensional-arrays.
The following statement declares a two-dimensional array 50 by 50 array within a procedure.
Dim AvgMarks ( 50, 50)
It is also possible to define the lower limits for one or both the dimensions as for fixed size arrays. An
example for this is given here.
Dim Marks ( 101 To 200, 1 To 100)
An example for three dimensional-array with defined lower limits is given below.
Dim Details( 101 To 200, 1 To 100, 1 To 100)
Conversion To Function
Boolean Cbool
Byte Cbyte
Currency Ccur
Date Cdate
Decimals Cdec
Double CDbl
Integer Cint
Long CLng
Single CSng
String CStr
Variant Cvar
Error CVErr
A conversion function should always be placed at the right hand side of the calculation statement.
Visual Basic Built-in Functions
Many built-in functions are offered by Visual Basic fall under various categories. These functions are
procedures that return a value. The functions fall into the following basic categories that will be discussed
in the follwing sections at length.
• Date and Time Functions
• Format Function
• String Functions
Function Description
DateAdd ( ) Returns a date to which a specific interval has been added
DateDiff ( ) Returns a Long data type value specifying the interval between the
two values
DatePart ( ) Returns an Integer containing the specified part of a given date
DateValue ( ) Converts a string to a Date
TimeValue ( ) Converts a string to a time
DateSerial ( ) Returns a date for specified year, month and day
DateDiff Function
The DateDiff function returns the intervals between two dates in terms of years, months or days. The
syntax for this is given below.
DateDiff (interval, date1, date2[, firstdayofweek[, firstweekofyear]])
Format Function
The format function accepts a numeric value and converts it to a string in the format specified by the
format argument. The syntax for this is given below.
Format (expression[, format[, firstdayofweek[, firstweekofyear]]])
The Format function syntax has these parts:
Part Description
Expression Required any valid expression
format Optional. A valid named or user-defined format expression.
firstdayofweek Optional. A contant that specifies the first day of the week.
firstweekofyear Optional. A contant that specifies the first week of the year
Building and Extracting Date and Time Values - VB6 Date & Time
There are many ways to assemble a Date value. For example, you can use a Date constant, such as the
following:
StartDate = #10/17/2008 9:25:33 P.M.#
but more often you'll build a Date value using one of the many functions that VBA gives you. The
DateSerial function builds a Date value from its year/month/day components; similarly, the TimeSerial
function builds a Time value from its hour/minute/second components:
Print DateSerial(2008, 10, 17) ' Displays "10/17/2008"
Print TimeSerial(12, 20, 30) ' Displays "12:20:30 P.M."
' Note that they don't raise errors with invalid arguments.
Print DateSerial(2008, 4, 31) ' Displays "5/1/2008"
The DateSerial function is also useful for determining indirectly whether a particular year is a leap year:
Function IsLeapYear(year As Integer) As Boolean
' Are February 29 and March 1 different dates?
IsLeapYear = DateSerial(year, 2, 29) <> DateSerial(year, 3, 1)
End Function
The DateValue and TimeValue functions return the date or time portions of their argument, which can be
a string or a Date expression:
' The date a week from now
Print DateValue(Now + 7) ' Displays "10/17/2008"
A bunch of VBA functions let you extract date and time information from a Date expression or variable.
The Day, Month, and Year functions return date values, whereas the Hour, Minute, and Second functions
return time values:
' Get information about today's date.
y = Year(Now): m = Month(Now): d = Day(Now)
' These functions also support any valid date format.
Print Year("10/17/2008 9:25:33 P.M.") ' Displays "2008"
The Weekday function returns a number in the range 1 through 7, which corresponds to the day of the
week of a given Date argument:
Print Weekday("10/17/2008") ' Displays "6" (= vbFriday)
The Weekday function returns 1 when the date is the first day of the week. This function is locale aware,
which means that under different localizations of Microsoft Windows it could consider the first day of the
week to be different from vbSunday. In most cases, this condition doesn't affect the structure of your
code. But if you want to be sure that 1 means Sunday, 2 means Monday, and so on, you can force the
function to return a consistent value under all Windows systems, as follows:
Print Weekday(Now, vbSunday)
Although using the optional second argument forces the function to return the correct value, it doesn't
change the system localization. If you next call the Weekday function without the second argument, it will
still consider the first day of the week to be what it was before.
Finally you can extract any date and time information from a Date value or expression using the DatePart
function, for which the syntax is
Result = DatePart(Interval, Date, [FirstDayOfWeek], [FirstWeekOfYear])
You'll rarely need to resort to this function because you can do most of your calculations using the other
functions I've shown you so far. In two cases, however, this function is really useful:
' The quarter we are in
Print DatePart("q", Now) ' Displays "3"
' The week number we are in (# of weeks since Jan 1st)
Print DatePart("ww", Now) ' Displays "33"
The first argument can be one of the String constants listed in the following table. For more information
about the two optional arguments, see the description of the DateAdd function in the next section.
Possible values for the interval argument in DatePart, DateAdd, and DateDiff functions.
Setting Description
"yyyy" Year
"q" Quarter
"m" Month
"y" Day of the year (same as d)
"d" Day
"w" Weekday
"ww" Week
"h" Hour
"n" Minute
"s" Second
Properties
Enabled specifies whether user can interact with this control or not
Index Specifies the control array index
If this control is set to True user can use it else if this control is set to false
Locked
the control cannot be used
Specifies the maximum number of characters to be input. Default value is
MaxLength
set to 0 that means user can input any number of characters
MousePointer Using this we can set the shape of the mouse pointer when over a TextBox
By setting this property to True user can have more than one line in the
Multiline
TextBox
PasswordChar This is to specify mask character to be displayed in the TextBox
ScroolBars This to set either the vertical scrollbars or horizontal scrollbars to make
appear in the TextBox. User can also set it to both vertical and horizontal.
This property is used with the Multiline property.
Text Specifies the text to be displayed in the TextBox at runtime
ToolTipIndex This is used to display what text is displayed or in the control
By setting this user can make the Textbox control visible or invisible at
Visible
runtime
Method
SetFocus Transfers focus to the TextBox
Event procedures
Change Action happens when the TextBox changes
Click Action happens when the TextBox is clicked
GotFocus Action happens when the TextBox receives the active focus
LostFocus Action happens when the TextBox loses it focus
KeyDown Called when a key is pressed while the TextBox has the focus
KeyUp Called when a key is released while the TextBox has the focus
A demonstration program that lets you experiment with the new Visual Basic Validate features
Private Sub txtNumeric_Validate(Cancel As Boolean)
If Not IsNumeric(txtNumeric.Text) Then
Cancel = True
ElseIf CDbl(txtNumeric.Text) < 1 Or CDbl(txtNumeric.Text) > 1000 Then
Cancel = True
End If
If Cancel Then
MsgBox "Please enter a number in range [1-1000]", vbExclamation
End If
End Sub
In some circumstances, you might want to programmatically validate the control that has the focus without
waiting for the user to move the input focus. You can do it with the form's ValidateControls method, which
forces the Validate event of the control that has the input focus. Typically, you do it when the user closes
the form:
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
' You can't close this form without validating the current field.
If UnloadMode = vbFormControlMenu Then
On Error Resume Next
ValidateControls
If Err = 380 Then
' The current field failed validation.
Cancel = True
End If
End If
End Sub
Checking the UnloadMode parameter is important; otherwise, your application will mistakenly execute a
ValidateControls method when the user clicks on the Cancel button. Note that ValidateControls returns an
error 380 if Cancel was set in the Validate event procedure of the control that had the focus.
Visual Basic 6's validation scheme has two flaws, though. If your form has a CommandButton whose
Default property is set to True, pressing the Enter key while the input focus is on another control results in
a click on the CommandButton control but doesn't fire a Validate event, even if the CausesValidation
property of the CommandButton control is set to True. The only way to solve this problem is to invoke the
ValidateControls method from within the default CommandButton control's Click event procedure.
The second flaw is that the Validate event doesn't fire when you're moving the focus from a control whose
CausesValidation property is False, even if the control that receives the focus has its CausesValidation
property set to True.
The new Visual Basic 6 validation mechanism is simple and can be implemented with little effort. But it
isn't the magic answer to all your validation needs. In fact, this technique can only enforce field-level
validation; it does nothing for record-level validation. In other words, it ensures that one particular field is
correct, not that all fields in the form contain valid data. To see what I mean, run the demonstration
program, enter a string in the first field, and press Alt+F4 to close the form. Your code won't raise an
error, even if the second field doesn't contain a valid number! Fortunately, it doesn't take much to create a
generic routine that forces each control on the form to validate itself:
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
' You can't close this form without validating all the fields on it.
If UnloadMode = vbFormControlMenu Then
On Error Resume Next
Dim ctrl As Control
' Give the focus to each control on the form, and then
' validate it.
For Each ctrl In Controls
Err.Clear
ctrl.SetFocus
If Err = 0 Then
' Don't validate controls that can't receive input focus.
ValidateControls
If Err = 380 Then
' Validation failed, refuse to close.
Cancel = True: Exit Sub
End If
End If
Next
End If
End Sub
The CausesValidation property and the Validate event are shared by all the intrinsic controls that are able
to get the focus as well as by most external ActiveX controls, even those not specifically written for Visual
Basic. This is possible because they are extender features, provided by the Visual Basic runtime to all the
controls placed on a form's surface.
One Visual Basic operator has great potential when it comes time to validate complex strings but is
neglected by most Visual Basic developers. Let's say you have a product code that consists of two
uppercase characters followed by exactly three digits. You might think that you need some complex string
functions to validate such a string until you try the Like operator, as follows:
If "AX123" Like "[A-Z][A-Z]###" Then Print "OK"
When compared to TextBox controls, these controls are really simple. Not only do they expose relatively
few properties, they also support a limited number of events, and you don't usually write much code to
manage them.
CommandButton Controls in VB6
Using CommandButton controls is trivial. In most cases, you just draw the control on the form's surface,
set its Caption property to a suitable string (adding an & character to associate a hot key with the control if
you so choose), and you're finished, at least with user-interface issues. To make the button functional,
you write code in its Click event procedure, as in this fragment:
Private Sub Command1_Click()
' Save data, then unload the current form.
Call SaveDataToDisk
Unload Me
End Sub
You can use two other properties at design time to modify the behavior of a CommandButton control. You
can set the Default property to True if it's the default push button for the form (the button that receives a
click when the user presses the Enter key—usually the OK or Save button). Similarly, you can set the
Cancel property to True if you want to associate the button with the Escape key.
The only relevant CommandButton's run-time property is Value, which sets or returns the state of the
control (True if pressed, False otherwise). Value is also the default property for this type of control. In
most cases, you don't need to query this property because if you're inside a button's Click event you can
be sure that the button is being activated. The Value property is useful only for programmatically clicking
a button:
This fires the button's Click event.
Command1.Value = True
The CommandButton control supports the usual set of keyboard and mouse events (KeyDown, KeyPress,
KeyUp, MouseDown, MouseMove, MouseUp, but not the DblClick event) and also the GotFocus and
LostFocus events, but you'll rarely have to write code in the corresponding event procedures.
The Timer, Line, Shape and OLE Controls in Visual Basic 6 (VB6)
The Timer Control
A Timer control is invisible at run time, and its purpose is to send a periodic pulse to the current
application. You can trap this pulse by writing code in the Timer's Timer event procedure and take
advantage of it to execute a task in the background or to monitor a user's actions. This control exposes
only two meaningful properties: Interval and Enabled. Interval stands for the number of milliseconds
between subsequent pulses (Timer events), while Enabled lets you activate or deactivate events. When
you place the Timer control on a form, its Interval is 0, which means no events. Therefore, remember to
set this property to a suitable value in the Properties window or in the Form_Load event procedure:
Private Sub Form_Load()
Timer1.Interval = 500 ' Fire two Timer events per second.
End Sub
Timer controls let you write interesting programs with just a few lines of code. The typical (and abused)
example is a digital clock. Just to make things a bit more compelling, I added flashing colons:
Private Sub Timer1_Timer()
Dim strTime As String
strTime = Time$
If Mid$(lblClock.Caption, 3, 1) = ":" Then
Mid$(strTime, 3, 1)= " "
Mid$(strTime, 6, 1) = " "
End If
lblClock.Caption = strTime
End Sub
You must be careful not to write a lot of code in the Timer event procedure because this code will be
executed at every pulse and therefore can easily degrade your application's performance. Just as
important, never execute a DoEvents statement inside a Timer event procedure because you might cause
the procedure to be reentered, especially if the Interval property is set to a small value and there's a lot of
code inside the procedure.
Timer controls are often useful for updating status information on a regular basis. For example, you might
want to display on a status bar a short description of the control that currently has the input focus. You
can achieve that by writing some code in the GotFocus event for all the controls on the form, but when
you have dozens of controls this will require a lot of code (and time). Instead, at design time load a short
description for each control in its Tag property, and then place a Timer control on the form with an Interval
setting of 500. This isn't a time-critical task, so you can use an even larger value. Finally add two lines of
code to the control's Timer event:
Private Sub Timer1_Timer()
On Error Resume Next
lblStatusBar.Caption = ActiveControl.Tag
End Sub
Simple combo
Dropdown combo Dropdown list
Text (empty)
TextBox
Name txtName
Caption (empty)
Label Name lblDisplay
Border Style 1 Fixed Single
Caption Add
CommandButton
Name cmdAdd
CommandButton Caption Remove
Name cmdRemove
Caption Clear
CommandButton
Name cmdClear
Caption Exit
CommandButton
Name cmdExit
The following event procedures are entered for the TextBox and CommandButton controls.
Private Sub txtName_Change()
If (Len(txtName.Text) > 0) Then 'Enabling the Add button
'if atleast one character
'is entered
cmdAdd.Enabled = True
End If
End Sub
Private Sub cmdAdd_Click()
lstName.AddItem txtName.Text 'Add the entered the characters to the list box
The ScrollBar is a commonly used control, which enables the user to select a value by positioning it at the
desired location. It represents a set of values. The Min and Max property represents the minimum and
maximum value. The value property of the ScrollBar represents its current value, that may be any integer
between minimum and maximum values assigned.
The HScrollBar and the VScrollBar controls are perfectly identical, apart from their different orientation.
After you place an instance of such a control on a form, you have to worry about only a few properties:
Min and Max represent the valid range of values, SmallChange is the variation in value you get when
clicking on the scroll bar's arrows, and LargeChange is the variation you get when you click on either side
of the scroll bar indicator. The default initial value for those two properties is 1, but you'll probably have to
change LargeChange to a higher value. For example, if you have a scroll bar that lets you browse a
portion of text, SmallChange should be 1 (you scroll one line at a time) and LargeChange should be set to
match the number of visible text lines in the window.
The most important run-time property is Value, which always returns the relative position of the indicator
on the scroll bar. By default, the Min value corresponds to the leftmost or upper end of the control:
' Move the indicator near the top (or left) arrow.
VScroll1.Value = VScroll1.Min
' Move the indicator near the bottom (or right) arrow.
VScroll1.Value = VScroll1.Max
While this setting is almost always OK for horizontal scroll bars, you might sometimes need to reverse the
behavior of vertical scroll bars so that the zero is near the bottom of your form. This arrangement is often
desirable if you want to use a vertical scroll bar as a sort of slider. You obtain this behavior by simply
inverting the values in the Min and Max properties. (In other words, it's perfectly legal for Min to be greater
than Max.)
There are two key events for scrollbar controls: the Change event fires when you click on the scroll bar
arrows or when you drag the indicator; the Scroll event fires while you drag the indicator. The reason for
these two distinct possibilities is mostly historical. First versions of Visual Basic supported only the
Change event, and when developers realized that it wasn't possible to have continuous feedback when
users dragged the indicator, Microsoft engineers added a new event instead of extending the Change
event. In this way, old applications could be recompiled without unexpected changes in their behavior. At
any rate, this means that you must often trap two distinct events:
' Show the current scroll bar's value.
Private VScroll1_Change()
Label1.Caption = VScroll1.Value
End Sub
Private VScroll1_Scroll()
Label1.Caption = VScroll1.Value
End Sub
The example shown in the following figure uses three VScrollBar controls as sliders to control the
individual RGB (red, green, blue) components of a color. The three scroll bars have their Min property set
to 255 and their Max property set to 0, while their SmallChange is 1 and LargeChange is 16. This
example is also a moderately useful program in itself because you can select a color and then copy its
numeric value to the clipboard and paste it in your application's code as a decimal value, a hexadecimal
value, or an RGB function.
Caption 1
CommandButto
Name cmd
n
Index 0
Caption 2
CommandButto
Name cmd
n
Index 1
Caption 3
CommandButto
Name cmd
n
Index 2
Caption 4
CommandButto
Name cmd
n
Index 3
Caption 5
CommandButto
Name cmd
n
Index 4
Caption 6
CommandButto
Name cmd
n
Index 5
Caption 7
CommandButto
Name cmd
n
Index 6
Caption 8
CommandButto
Name cmd
n
Index 7
Caption 9
CommandButto
Name cmd
n
Index 8
Caption 0
CommandButto
Name cmd
n
Index 10
CommandButto Caption .
Name
n cmd
Index
11
CommandButto Caption AC
n Name cmdAC
CommandButto Caption +
n Name cmdPlus
CommandButto Caption -
n Name cmdMinus
CommandButto Caption *
n Name cmdMultiply
CommandButto Caption /
n Name cmdDivide
Name txtDisplay
TextBox
Text ( empty )
CommandButto Caption =
n Name cmdEqual
Case "+"
Result = Previous + Current
txtDisplay.Text = Result
Case "-"
Result = Previous - Current
txtDisplay.Text = Result
Case "*"
Result = Previous * Current
txtDisplay.Text = Result
Case "/"
Result = Previous / Current
txtDisplay.Text = Result
End Select
Current = Result
End Sub
Save and run the project. On clicking digits of user's choice and an operator button, the output appears.
Iterating on the Items of a Control Array
Control arrays often let you save many lines of code because you can execute the same statement, or
group of statements, for every control in the array without having to duplicate the code for each distinct
control. For example, you can clear the contents of all the items in an array of TextBox controls as
follows:
For i = txtFields.LBound To txtFields.UBound
txtFields(i).Text = ""
Next
Here you're using the LBound and UBound methods exposed by the control array object, which is an
intermediate object used by Visual Basic to gather all the controls in the array. In general, you shouldn't
use this approach to iterate over all the items in the array because if the array has holes in the Index
sequence an error will be raised. A better way to loop over all the items of a control array is using the For
Each statement:
Dim txt As TextBox
For Each txt In txtFields
txt.Text = ""
Next
A third method exposed by the control array object, Count, returns the number of elements it contains. It
can be useful on several occasions (for example, when removing all the controls that were added
dynamically at run time):
' This code assumes that txtField(0) is the only control that was
' created at design time (you can't unload it at run time).
Do While txtFields.Count > 1
Unload txtFields(txtFields.UBound)
Loop
Three of the controls on the ToolBox let you access the computer's file system. They are DriveListBox,
DirListBox and FileListBox controls (see below figure) , which are the basic blocks for building dialog
boxes that display the host computer's file system. Using these controls, user can traverse the host
computer's file system, locate any folder or files on any hard disk, even on network drives. The files are
controls are independent of one another, and each can exist on it's own, but they are rarely used
separately. The files controls are described next.
In a nutshell, the DriveListBox control is a combobox-like control that's automatically filled with your
drive's letters and volume labels. The DirListBox is a special list box that displays a directory tree. The
FileListBox control is a special-purpose ListBox control that displays all the files in a given directory,
optionally filtering them based on their names, extensions, and attributes.
These controls often work together on the same form; when the user selects a drive in a DriveListBox, the
DirListBox control is updated to show the directory tree on that drive. When the user selects a path in the
DirListBox control, the FileListBox control is filled with the list of files in that directory. These actions don't
happen automatically, however—you must write code to get the job done.
After you place a DriveListBox and a DirListBox control on a form's surface, you usually don't have to set
any of their properties; in fact, these controls don't expose any special property, not in the Properties
window at least. The FileListBox control, on the other hand, exposes one property that you can set at
design time—the Pattern property. This property indicates which files are to be shown in the list area: Its
default value is *.* (all files), but you can enter whatever specification you need, and you can also enter
multiple specifications using the semicolon as a separator. You can also set this property at run time, as
in the following line of code:
File1.Pattern = "*.txt;*.doc;*.rtf"
Following figure shows three files controls are used in the design of Forms that let users explore the
entire structure of their hard disks.
• DriveListBox : Displays the names of the drives within and connected to the PC. The basic
property of this control is the drive property, which set the drive to be initially selected in the control or
returns the user's selection.
• DirListBox : Displays the folders of current Drive. The basic property of this control is the Path
property, which is the name of the folder whose sub folders are displayed in the control.
• FileListBox : Displays the files of the current folder. The basic property of this control is also
called Path, and it's the path name of the folder whose files are displayed.
The three File controls are not tied to one another. If you place all three of them on a Form, you will see
the names of all the folders under the current folder, and so on. Each time you select a folder in the
DirlistBox by double clicking its name, its sub folders are displayed. Similarly , the FileListBox control will
display the names of all files in the current folder. Selecting a drive in the DriveListBox control, however
this doesn't affect the contents of the DirListBox.
To connect to the File controls, you must assign the appropriate values to the properties. To compel the
DirListBox to display the folders of the selected drive in the DriveListBox, you must make sure that each
time the user selects another drive, the Path property of the DirListBox control matches the Drive property
of the DriveListBox.
After these preliminary steps, you're ready to set in motion the chain of events. When the user selects a
new drive in the DriveListBox control, it fires a Change event and returns the drive letter (and volume
label) in its Drive property. You trap this event and set the DirListBox control's Path property to point to
the root directory of the selected drive:
Private Sub Drive1_Change()
' The Drive property also returns the volume label, so trim it.
Dir1.Path = Left$(Drive1.Drive, 1) & ":\"
End Sub
When the user double-clicks on a directory name, the DirListBox control raises a Change event; you trap
this event to set the FileListBox's Path property accordingly:
Private Sub Dir1_Change()
File1.Path = Dir1.Path
End Sub
Finally, when the user clicks on a file in the FileListBox control, a Click event is fired (as if it were a regular
ListBox control), and you can query its Filename property to learn which file has been selected. Note how
you build the complete path:
Filename = File1.Path
If Right$(Filename, 1) <> "\" Then Filename = Filename & "\"
Filename = Filename & File1.Filename
The DirListBox and FileListBox controls support most of the properties typical of the control they derive
from—the ListBox control—including the ListCount and the ListIndex properties and the Scroll event. The
FileListBox control supports multiple selection; hence you can set its MultiSelect property in the
Properties window and query the SelCount and Selected properties at run time.
The FileListBox control also exposes a few custom Boolean properties, Normal, Archive, Hidden,
ReadOnly, and System, which permit you to decide whether files with these attributes should be listed.
(By default, the control doesn't display hidden and system files.) This control also supports a couple of
custom events, PathChange and PatternChange, that fire when the corresponding property is changed
through code. In most cases, you don't have to worry about them, and I won't provide examples of their
usage.
The problem with the DriveListBox, DirListBox and FileListBox controls is that they're somewhat outdated
and aren't used by most commercial applications any longer. Moreover, these controls are known to work
incorrectly when listing files on network servers and sometimes even on local disk drives, especially when
long file and directory names are used. For this reason, I discourage you from using them and suggest
instead that you use the Common Dialog controls for your FileOpen and FileSave dialog boxes. But if you
need to ask the user for the name of a directory rather than a file, you're out of luck because—while
Windows does include such a system dialog box, named BrowseForFolders dialog—Visual Basic still
doesn't offer a way to display it (unless you do some advanced API programming). Fortunately, Visual
Basic 6 comes with a new control—the ImageCombo control—that lets you simulate the appearance of
the DriveListBox control. It also offers you a powerful library—the FileSystemObject library—that
completely frees you from using these three controls, if only as hidden controls that you use just for
quickly retrieving information on the file system.
Caption Bold
CheckBox
Name chkBold
Caption Italic
CheckBox
Name chkItalic
Caption Underline
CheckBox
Name chkUnderline
Caption Red
OptionButton
Name optRed
Caption Blue
OptionButton
Name optBlue
Caption Green
OptionButton
Name optGreen
Name txtDisplay
TextBox
Text (empty)
Caption Exit
CommandButton
Name cmdExit
By default, Visual Basic suggests the name of the first Form created when the project started.
Loading and Unloading Forms
In order to load and unload the forms, Load and Unload statements are used. The Load statement has
the following syntax :
Load FormName
And the Unload statement has the following syntax :
Unload FormName
The FormName variable is the name of the Form to be loaded or unloaded. Unlike the Show method
which cares of both loading and displaying the Form, the load statement doesn't show the Form. You
have to call the Form's Show method to display it on the desktop.
Showing and Hiding Forms
Show method is used to Show a Form. If the Form is loaded but invisible, the Show method is used to
bring the Form on Top every other window. If the Form is not loaded, the Show method loads it and then
displays it.
Syntax of the Show method of the Form
FormName.Show mode
The FormName variable is the Form's name, and the optional argument mode determines whether the
Form will be Modal or not. It can have one of the following syntax :
* 0-Modeless (default)
* 1-Modal
Modeless Forms are the normal Forms. Modeless Forms interact with the user and the user allowed to
switch to any other Form of the application. If you do not specify the optional mode argument, by default
the mode is set to modeless.
The Modal Forms takes the total control of the application where user cannot switch to any other Forms in
the application unless the Form is closed. A modal Form, thus, must have a Close button or some means
to close the Form in order to return to the Form where the Modal Form was loaded.
Hiding Forms
The Hide method is used to hide a Form. The following is the syntax of the Hide Method.
FormName.Hide
To hide a Form from within its own code, the following code can be used.
Me.Hide
You must understand that the Forms that are hidden are not unloaded ; they remains in the memory and
can be displayed instantly with the Show Method. When a Form is hidden, you can still access its
properties and code. For instance, you can change the settings of its Control Properties or call any Public
functions in the Form.
The following is an example illustrates the Show method and Mode statement
* Open a new Project and save the Project
Design the application as shown below
Caption Form1
Form
Name frm1
Caption Form2
Form
Name frm2
Caption Form3
Form
Name frm3
Click on a button
Caption
Label to display a Form
Name
Label1
The following code is typed in the Click event of the command buttons
Run the application. Clicking on the buttons will display the Forms respectively. But you can see that in
the cmd2_Click( ) event additionally VbModal argument has been added. You can see the difference after
you display the forms by clicking on the command buttons. You can notice that you cannot switch to any
other Forms in the application unless you close the Form3. (Download the source code)
Finding out the difference between Unload and Hide method
To know what the difference is between Unload and Hide methods we will do an example. Open a new
project and save the project. Draw two buttons on the form and name those as shown above.
An expanded menu
One of the most annoying defects of the Menu Editor tool is that it doesn't permit you to reuse the menus
you have already written in other applications. It would be great if you could open another instance of the
Visual Basic IDE, copy one or more menu items to the clipboard, and then paste those menu items in the
application under development. You can do that with controls and with pieces of code, but not with
menus! The best thing you can do in Visual Basic is load the FRM file using an editor such as Notepad,
find the portion in the file that corresponds to the menu you're interested in, load the FRM file you're
developing (still in Notepad), and paste the code there. This isn't the easiest operation, and it's also
moderately dangerous: If you paste the menu definition in the wrong place, you could make your FRM
form completely unreadable. Therefore, always remember to make backup copies of your forms before
trying this operation.
Better news is that you can add a finished menu to a form in your application with just a few mouse clicks.
All you have to do is activate the Add-In Manager from the Add-Ins menu, choose the VB 6 Template
Manager, and tick the Loaded/Unloaded check box. After you do that, you'll find three new commands in
the Tools menu: Add Code Snippet, Add Menu, and Add Control Set. Visual Basic 6 comes with a few
menu templates, as you can see in the following figure, that you might find useful as a starting point for
building your own templates. To create your menu templates, you only have to create a form with the
complete menu and all the related code and then store this form in the \Templates\Menus directory. (The
complete path, typically c:\Program Files\Microsoft Visual Studio\VB98\Template, can be found in the
Environment tab of the Options dialog box on the Tools menu. The Template Manager was already
available with Visual Basic 5, but it had to be installed manually and relatively few programmers were
aware of its existence.
Enabled : specifies whether a menu is disabled or not. If you see a disabled command in a menu that
means that feature is not available. The Visible checkbox specifies whether the menu is visible or not.
To add commands to the Form's menu bar, enter a caption and a name for each command. As soon as
you start typing the command's caption, it also appears in a new line in the list at the bottom of the Menu
Editor window. To add more commands click Enter and type the Caption and the Name.
Creating Menus
Open a new Project and save the form as menu.frm and save the project as menu.vbp.
Choose Tools ››› Menu Editor and type the menu items as shown below.
Caption Name
File mnuFile
Open mnuOpen
Save mnuSave
Exit mnuExit
Edit mnuEdit
Copy mnuCopy
Cut mnuCut
Paste mnuPaste
Run the application by pressing F5. You can see that you can select a men.
Syntax :
memory_variable = InputBox (prompt[,title][,default])
memory_variable is a variant data type but typically it is declared as string, which accept the message
input by the users. The arguments are explained as follows:
• Prompt - String expression displayed as the message in the dialog box. If prompt consists of
more than one line, you can separate the lines using the vbCrLf constant
• Title - String expression displayed in the title bar of the dialog box. If you omit the title, the
application name is displayed in the title bar
• default-text - The default text that appears in the input field where users can use it as his
intended input or he may change to the message he wish to key in.
• x-position and y-position - the position or the coordinate of the input box.
Following example demonstrates the use of InputBox function
* Open a new project and save the Form as InputBox.frm and save the Project as InputBox.vbp
* Design the application as shown below.
Caption ( empty)
Label
Name lbl2
BorderStyle 1-Fixed Single
CommandButton Caption OK
Name cmdOK
Here I have entered "Hello World" in text field. As soon as you click OK the output is shown as shown
below
MessageBox Function in Visual Basic 6 (VB6)
Displays a message in a dialog box and wait for the user to click a button, and returns an integer
indicating which button the user clicked.
Following is an expanded MessageBox
Syntax :
MsgBox ( Prompt [,icons+buttons ] [,title ] )
memory_variable = MsgBox ( prompt [, icons+ buttons] [,title] )
Prompt : String expressions displayed as the message in the dialog box. If prompt consist of more than
one line, you can separate the lines using the vbrCrLf constant.
Icons + Buttons : Numeric expression that is the sum of values specifying the number and type of
buttons and icon to display.
Title : String expression displayed in the title bar of the dialog box. If you omit title, the application name
is placed in the title bar.
Icons
Constant Value Description
vbCritical 16 Display Critical message icon
vbQuestion 32 Display Warning Query icon
vbExclamation 48 Display Warning message icon
vbInformation 64 Display information icon
Buttons
Constant Value Description
vbOkOnly 0 Display OK button only
vbOkCancel 1 Display OK and Cancel buttons
Display Abort, Retry and Ignore
vbAbortRetryIgnore 2
buttons
Display Yes, No and Cancel
vbYesNoCancel 3
buttons
vbYesNo 4 Display Yes and No buttons
vbRetryCancel 5 Display Retry and Cancel buttons
Return Values
Constant Value Description
vbOk 1 Ok Button
vbCancel 2 Cancel Button
vbAbort 3 Abort Button
vbRetry 4 Retry Button
vbIgnore 5 Ignore Button
vbYes 6 Yes Button
vbNo 7 No Button
Following is an example illustrates the use of message boxes
* Open a new Project and save the Form as messageboxdemo.frm and save the Project as
messageboxdemo.vbp
* Design the application as shown below.
Object Property Setting
Form Caption MessageBoxDemo
Name frmMessageBoxDemo
End If
End If
End If
End Sub
Following code is entered in the cmdExit_Click ( ) event
Private Sub cmdExit_Click()
answer = MsgBox("Do you want to quit?", vbExclamation + vbYesNo, "Confirm")
If answer = vbYes Then
End
Else
MsgBox "Action canceled", vbInformation, "Confirm"
End If
End Sub
Save and run the application. You can notice the different type of message box types are used to perform
an action
Visual Basic responds to various mouse events, which are recognized by most of the controls. The main
events are MouseDown, MouseUp and MouseMove. MouseDown occurs when the user presses any
mouse button and MouseUp occurs when the user releases any mouse button. These events use the
arguments button, Shift, X, Y and they contain information about the mouse's condition when the button is
clicked.
The first argument is an integer called Button. The value of the argument indicates whether the left, right
or middle mouse button was clicked. The second argument in an integer called shift. The value of this
argumnet indicates whether the mouse button was clicked simultaneously with the Shift key, Ctrl key or
Alt key. The third and fourth arguments X and Y are the coordinates of the mouse location at the time the
mouse button was clicked. As the Form_MouseDown( ) is executed automatically whenever the
mouse button is clicked inside the Form's area the X, Y co-ordinates are referenced to the form.
Positioning a control
MouseDown is the commonly used event and it is combined wiyth the move method to move an Image
control to different locations in a Form. The following application illustrates the movement of objects
responding to move events. it makes use of two OptionButton Controls, two image controls and a
CommandButton. The application is designed in such a way that when an OptionButton is selected, the
corresponding image control is placed anywhere in the form whenever it is clicked.
Open a new standard EXE project and save the Form as Move.frm and save the project as Move.vbp
Design the Form as shown below.
The follwoing code is entered in the general declarations section of the Form.
Option Explicit
The following code is entered in the Form_MouseDown( ) event
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single,
Y As Single)
If optCredit = True Then
imgCredit.Move X, Y
Else
imgCash.Move X, Y
End If
End Sub
Run the application by keying in F5. You can notice that when the mouse is clicked on the form
somewhere, the selected image moves to that clicked location. This is shown in the below figure.