2. Data Types of Variables
The data type of a variable is determined by the "As"
keyword. If the As keyword is omitted, the data type is
a "Variant".
The following illustrates the basic data types that may
be used:
Dim unkown As Variant
Dim atoms As Double
Dim tinyNumber As Byte
Dim unkown As Variant
3. DataTypes:
Byte : Stores an integer in the range 0 to 255 (8 bits).
Integer: Stores an integer (whole number) in the range
-32768 to +32767 (16 bits)
Long : Stores an integer in the range -2,147,483,648
to +2,147,483,647 (32 bits
Single : Stores a single-precision floating point
number, accurate
to 8 significant digits (32 bits).
Double: Stores a double-precision floating point
number,
accurate to 16 significant digits (64 bits).
String : Stores a sequence of up to 63,000 characters.
Date : Stores a Date.
Variant: data type will change on what value is assigned to the
variable
4. Declaring Variables
If no data type is specified when declaring a variable, its default
type will be a Variant. If more that one variable is declared on
the same line, the data type must be provided for each variable.
In the following example, x has no data type so will be declared
as a Variant.
Dim x, y As Integer or (Dim x As Integer, y As Integer)
The following declares the variables x and y as Integers.
Constants
A Constant value never changes. Visual Basic has some built in
constants, such as, vbCrLf, to insert a carriage return / line feed
on an output stream. Constants are declared with the Const
keyword.
Const deadline As Date = #1/20/2002#
Once the constant has been assigned a value, the value can't
be changed. Attempting to re-assign a value will result in a run-
time error.
5. Specifying a Range
You may also specify minimum and maximum index
numbers using the "To" keyword. This is preferable to
using Option Base, as it allows other arrays to use an
Index of zero. The following example declares an
array with 11 elements, indexed 1999 to 2009.
Dim surveyYear(1999 To 2009) As Integer
To access an element, use the appropriate index
number. surveyYear(2002) = 6243
The boundaries of an array may be found using the
UBound and LBound functions.
For counter = LBound(surveyYear) To
UBound(surveyYear) ' Process surveyYear(counter)
Next Counter
If the Range of surveyYear is changed, the code will
6. Scope and Duration of Variables
The scope and duration of a variable is determined by
the keywords Dim, Redim, Static, Public or Private.
Whilst declarations can appear anywhere within the
body of code, it is good programming practice to
declare all variables at the beginningDeclaration
type
Scope & Duration
Dim Used to declare variables in procedures. Each time the
procedure is called, the data stored in variables declared
with this keyword are reset (eg. an Integer data type will
be reset to zero).
Static Used to declare variables in procedures. Each time the
procedure is called, the data stored in variables declared with
this keyword are retained.
Public Used to declare variables within a module. The variable is
available to all procedures in the project.
Private Used to declare variables within a module. The variable is
only available to procedures within the project.
7. The Array Function
The Array Function is used to populate a Variant data type with
an array of values.
Dim weekDay As Variant
weekDay = Array("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday")
Multi-Dimensional Arrays
Arrays may have more than one dimension. Each dimension in
separated by a comma and may be specified as a range. The
following example declares a simple two dimension 4 by 4 grid
(remember you get one more element that you specify).
Dim grid(3, 3) As Integer
Combinations of the two index numbers identify the different
elements. 'Place a '1' in the top left corner of the grid grid(0, 0)
= 1 'Place a '1' in the bottom right corner of the grid grid(3, 3) =
1
8. Control Arrays
A control array is an array of similar controls with the same
name identified by their index number. The easiest way to
create a control array is by copying the control with and pasting
it. Visual Basic asks if would like to create a control array if the
Index property is not set. Controls may be added dynamically at
run-time using the "Load" method. To do this, place a single
control on the form and set its Index property to zero. then
dynamically load further controls of that type.
Load picNode(1) picNode(1).Visible = True
Controls may be dynamically removed using the Unload
function.
Unload picNode(1)
Program Flow in Visual Basic
Structured programming is based around three basic
constructs: Sequence, Selection and Iteration. The Sequence
construct is the simplest, whereby statements are executed in
the order they're found in the code.
9. Dynamic Arrays
Arrays are resized using the ReDim statement. An
array may be resized any number of times, but
existing data is lost unless the Preserve option is
used. To use ReDim, arrays must be declared without
an initial size, and resized when they're first used.
Dim customer() As String
ReDim customer(10)
To redimension the array preserving existing vales,
use the "Preserve" keyword.
ReDim Preserve customer(20)
The "As" clause may be used to change the data type
of a Variant, unless the Preserve keyword is used. In
VB.Net, an initial size must be provided, and allows
the array to be resized.
10. Selection Constructs
The Selection constructs are used when the flow of
execution may flow down two or more paths.
The If Statement
The If statement is used to control the flow of execution
down one of two or more paths, depending on the result
of a logical test. The ElseIf statement may be used to
specify conditions should previous conditions be false,
and Else may be used should none of the above be true.
If grade < 40 Then
Debug.Print "Failed" Else
If grade < 75 Then
Debug.Print "Passed" Else Debug.Print "Excellent Pass“
End If
If statements can be nested, and the combined with
11. The Select Statement
The Select statement can be used when multiple If statements
become messy and difficult to read. Each Case statement is
evaluated from the top down. Should the Case statement be
true, the section of code associated with the condition is
executed. Case Else is used as a catch all. The following
example use the Select Case construct to move a Shape,
shpBlock, according to which arrow key is pressed on the
keyboard.
Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer)
Select Case KeyCode Case vbKeyUp
' Move the block up the form shpBlock.
Top = shpBlock.Top - 50 Case vbKeyDown
' Move the block down the form shpBlock.
Top = shpBlock.Top + 50 Case vbKeyLeft
' Move the block left on the form shpBlock.
Left = shpBlock.Left - 50 Case vbKeyRight
' Move the block right on the form shpBlock.
Left = shpBlock.Left + 50 Case Else
MsgBox "Incorrect Key", vbExclamation, "KeyDown Demonstration“
12. Iteration Constructs
The Iteration constructs are used when a block of code is
required to be executed continually until a condition is met.
Pre-Condition Loops
Pre-condition loops allow for a condition to be tested at the start of the
loop. This type of loop is used when you only want to execute the
block of code should the condition be true. For example, you would
only want to iterate through a RecordSet collection should the
RecordSet contain some records. Do While Not adoRS.EOF
Debug.Print adoRS.Fields.Value adoRS.MoveNext Loop The following
example of a pre-condition loop calculate the factorial of a number.
The value is taken from a TextBox, txtFactorial.
Private Sub cmdFactorial_Click()
Dim factorial As Long Dim counter As Integer Dim strAnswer As
String counter = Val(txtFactorial.Text) factorial = counter
Do While counter > 1
counter = counter - 1 factorial = factorial * counter Loop
strAnswer = "Factorial of " & txtFactorial.Text & " is " & factorial
MsgBox strAnswer, vbInformation, "Factorial“
13. Post-Condition Loops
Post-condition loops allow for a condition to be tested at
the end of the loop. This type of loop is used when you
want to execute the block of code at least once. This is
useful for validation. The following example prompts the
user for a number between 1 and 10.
Dim response As Integer
Do response = Val(InputBox("Enter a number between 1 and
10", "Number Cruncher"))
Loop While response < 1 Or response > 10
Counted Loops
Sometimes the number of iterations required are known
in advance. In this case a counted loop may be used.
Visual Basic provides a For ... Next construct to handle
counted loops. The following example prints the numbers
one to ten.
For counter = 1 To 10
Debug.Print counter & vbCrLf
15. 10. ListBox Control.
11. Horizontal and Vertical Scroll bars.
12. Timer Control.
13. DriveListBox, DirListBox, and
FileListBox.
14. Shape Control.
15. Line Control.
16. Image Control.
17. Data Control.
18. Object Linkking and Embedding
(OLE) Control.
16. The Pointer
The Pointer is not a control, but
is used to interact with the
controls on the form, allowing
you to move and resize them.
The Pointer is selected by
default. When a control is added
to the form, the focus reverts
back to the Pointer.
17. PictureBox Control
The PictureBox is used to display images or act as a
container to other controls. The three-letter mnemonic
for a PictureBox is pic (eg. picFace). The main event
for a PictureBox is the Click event. Pictures are
loaded into the PictureBox using the LoadPicture
function. The following example toggles between
face0.gif and face1.gif with each click of the mouse.
Private Sub picFace_Click()
Static toggle As Integer Dim strFileName As
String strFileName = "c:imagesface" & toggle &
".gif" picFace.Picture = LoadPicture(strFileName)
toggle = toggle Xor 1
End Sub
18. Label Control
The Label control is used to display text that
can't be changed directly by the user. Labels
are more commonly used to place captions
against other controls or store calculated
values. The three-letter mnemonic for a Label
is lbl (eg. lblPrompt). The default property of a
Label is Caption. The Caption property may
be set at design-time using the Properties
Window, and changed at run-time.
lblPrompt.Caption = "Changed at run-time"
Note: In VB.Net, the Caption property has
been dropped in favour of the Text property for
19. TextBox Control
The TextBox is used to display text that may be edited directly
by the user. The three-letter mnemonic for a TextBox is txt (eg.
txtData). The default event for a TextBox is "Change", and the
default property is "Text". The following example allows the
enter key to be used to tab to the next control in the tab order.
Unit II Visual Programming 5
Private Sub txtData_KeyDown(KeyCode As Integer, Shift
As Integer)
' Check for a carriage return If KeyCode = 13 Then ' Turn
off the beep and tab to the next focusable control
KeyCode = 0 SendKeys "{TAB}"
End If
End Sub
To allow text on more than one line, the Multiline Property
must be set to True. If the ScrollBars Property doesn't
allow a Horizontal ScrollBar, then the text will wrap. The
length of the Text property is limited to 2048 characters for
20. Frame Control
The Frame control is used to group controls and
provides a means of sub-dividing the Form visually.
The three-letter mnemonic for a Frame is fra (eg.
fraPaymentMethod). The default property is Caption,
which can be used to give context to the grouping (eg.
Payment Method). Controls should be drawn within
the Frame in order to be associated with the Frame.
When the control is associated, moving the Frame
also moves all of the associated controls. When
option buttons are used, only one may be selected on
the Form. Option Buttons placed in a Frame are
associated with the Frame, and are treated as a new
group.
21. CommandButton Control
The CommandButton is used by the user to
invoke some action. The three-letter mnemonic
for a CommandButton is cmd. The default event
for a CommandButton is "Click". The following
example uses a CommandButton to end the
program.
Private Sub cmdQuit_Click()
Dim response As Integer response = MsgBox("Are
you sure", vbQuestion + vbYesNo, "Quit")
If response = vbYes Then
End
End If
End Sub
22. CheckBox Control
The CheckBox control is used to give the user a choice of
yes/no multiple choice options. The three-letter mnemonic for a
CheckBox is chk The "Value" property may be used to
determine whether an item has been selected - a value of 1
indicates true, and a value of 0 Unit II Visual Programming 6
indicates false. The following example uses a command button
to determine which items have been selected from a control
array of CheckBoxes.
Private Sub cmdList_Click()
Dim counter As Integer
Dim strMsg As String
For counter = 0 To chkHobbies.UBound
If chkHobbies(counter).Value = 1 Then
strMsg = strMsg & chkHobbies(counter).Caption & vbCrLf
End If
Next counter MsgBox strMsg, vbInformation, "Selected
23. OptionButton Control
The OptionButton control is used to group options where the
user can only select only one. As only one item may be selected
OptionButtons are grouped in containers such as the Form,
Frame or PictureBox. The three-letter mnemonic for an
OptionButton is opt The "Value" property may be used to
determine whether an item has been selected - either True or
False.
The following example uses a CommandButton to determine which item has
been selected from a control array of OptionButtons:
Private Sub cmdPayment_Click()
Dim counter As Integer, selectedItem As Integer
Dim strMsg As String
For counter = 0 To optPaymentMethod.UBound
If optPaymentMethod(counter).Value = True Then
selectedItem = counter End If
Next counter strMsg =
optPaymentMethod(selectedItem).Caption MsgBox strMsg,
24. ComboBox Control
The ComboBox is a combination of a TextBox and a ListBox
control. Items may be added to the list at design-time using the
"List" property (<CTRL>+<ENTER> takes you to the next line to
add a new item). Items may be added to the list at run-time
using the AddItem method, and removed at run-time using the
RemoveItem method (see below for details). The "Clear"
method removes all items from the list. The three-letter
mnemonic for a ComboBox is cbo (eg. cboArtist). The "Style"
property determines which type of ComboBox is displayed from
a choice of three.
Private Sub cboArtist_Click()
MsgBox cboArtist.Text, vbInformation, "Selected Item"
End Sub
valu
e
constant description
1 vbComboDropDown A TextBox with an arrow to produce a dropdown
list
2 vbComboSimple A TextBox with a ListBox always displayed
beneath
3 vbComboDrop-
DownList
Restricts items in the TextBox to those in the list
The following example produces a MessageBox when a new item has been
selected from the list.
25. The RemoveItem Method
The RemoveItem method is used to remove items from either a ComboBox
or a ListBox. The RemoveItem method takes one parameter to indicate
which item is to be removed.
cboArtist.RemoveItem 0
removes the first item from the list. The RemoveItem method has no effect if
the ComboBox or ListBox is bound to a Data control. The individual items
may be accessed using their index number to identify their position in the list.
The following would display the fourth item in the list.
MsgBox cboArtist.List(3), vbInformation, "Artist"
The AddItem Method
The AddItem method is used to add items to either a ComboBox or a
ListBox. The AddItem method has no effect if the ComboBox or ListBox is
bound to a Data control. The AddItem method takes two parameters,
"name", and "Index", where Index is an optional parameter. The following
adds, "Garbage", to the end of the list, or to its correct sorted position of the
Sorted Property has been set to True. cboArtist.AddItem "Garbage" The
following example adds the item, "Blur", to position 3 within the list. The
Sorted Property must be set to False if you specify a position.
cboArtist.AddItem "Blur". The following example loads three artists into a list
at run-time.
Private Sub Form_Load() cboArtist.AddItem "Gorillaz"
26. ListBox Control
The ListBox displays a list of items that may be selected by the
user. If the number of items in the list exceeds the size of the list
box, scroll bars are added automatically. Items may be added to
the list at design-time using the "List" property
(<CTRL>+<ENTER> takes you to the next line to add a new
item. Items may be added to the list at run-time using the
AddItem method, and removed at run-time using the
RemoveItem method. Both AddItem, and RemoveItem work in
the same way as described above for the ComboBox. The
"Clear" method removes all items from the list. The three-letter
mnemonic for a ListBox is lst (eg. lstArtist). The "Style" property
may be used to add a CheckBox to each item in the list.
The following example produces a MessageBox when a new item has been
selected from the list. Private Sub lstArtist_Click()
Dim strMsg As String strMsg = lstArtist.List(lstArtist.ListIndex) MsgBox
strMsg, vbInformation, "Selected Item"
End Sub
valu
e
constant description
1 vbListBoxStandard A standard list
2 vbListBoxCheckbox A check box is added to each item in the list
27. HScroll and VScroll Control
Scroll bars provide a convenient way of navigating through
large amounts of information or providing a visual indication of a
value. The Min and Max properties allow you to specify the
minimum and maximum value of the scroll bar. The Value
property indicates the position of the thumb of the scrollbar in
relation to the Max and Min values. The SmallChange property
specifies how much to increment or decrement the value if you
click on the arrow, and the LargeChange property specifies how
much to increment or decrement the value if you click on the
track of the scroll bar. Visual Basic offers two scroll bars, a
horizontal scroll bar (HScroll), and a vertical scroll bar (VSroll)
A VScrollBar is placed vertically on the form. The three-letter
mnemonic for a VScrollBar is vsb (eg. vsbVolume). The default event
for a scroll bar is the Change event. A HScrollBar is placed horizontally
on the form. The three-letter mnemonic for a HScrollBar is hsb (eg.
hsbVolume). The default event for a scroll bar is the Change event. The
following example uses a Label to show the exact value of the scroll
bar.
Private Sub hsbVolume_Change()
lblVolume = hsbVolume.Value
28. Timer Control
The Timer control is visible at design-time, but not
shown at run-time. It is used for background
processing at intervals specified by the Interval
property. The Interval property takes an integer in the
range 0 to 65,535. The Interval is measured in
milliseconds, therefore a value of 1000 equals an
interval of one second. An Interval of 0 disables the
Timer control in VB 6, but not in VB.Net. To disable
the Timer, set the Enabled Property to False. Setting
it to True will enable it again. The three-letter
mnemonic for a Timer is tmr (eg. tmrMove). The
default event for a Timer is the Timer event. This
example moves a PictureBox around the form. To try
the example, add a PictureBox called picFace, and a
29. Private Sub tmrMove_Timer()
Const distance As Integer = 50 Static xDirection As Integer, yDirection
As Integer
' The first time this function is called, the Static ' variables with have a
value of 0
If xDirection = 0 Then
xDirection = 1 yDirection = 1
End If
' Move the picture around the form picFace.
Move picFace.Left + distance * xDirection, picFace.Top + distance *
yDirection ' Constrain to the form horizontally
If picFace.Left < 0 Or picFace.Left + picFace.Width > Me.ScaleWidth
Then
xDirection = xDirection * -1
End If
' Constrain to the form vertically
If picFace.Top < 0 Or picFace.Top + picFace.Height > Me.ScaleHeight
Then
yDirection = yDirection * -1
End If
End Sub
30. Object Linking and Embedding
(OLE) Control
The Object Linking and Embedding (OLE)
control allows you to insert an insertable
object into your application. When you
add the control to your form, you will be
given a list of insertable objects that can
be created from new on your machine
(eg. Paint Shop Pro) or you can select an
object from an existing file such as a
Word document. The three-letter
31. Data Control
The Data control allows data-aware controls to be
bound to Fields within a recordset, providing an
efficient solution for accessing a database without
writing any code. The Caption property will be
the name displayed on the Data control. The
DatabaseName property is used to store the location
and name of the database. The RecordSource
property is used to determine the name of the table or
stored procedure in the database. The three-letter
mnemonic for a Data control is dta (eg. dtaQuestion).
To bind a data-aware control to the Data control, set
the DataSource property of the data-aware control to
the name of the Data control (selected from a drop-
down list). Having set the DataSource, you can select
32. Image Control
The Image control is used to display a
picture. It doesn't contain as many
properties, methods and events as a
PictureBox but repaints faster as it uses
fewer system resources. The three-letter
mnemonic for an Image is img (eg.
imgFace).
The following example loads a picture into an Image
control:
33. Line Control
The Line control is used to display a line on a
form. The line is visible even when the form's
AutoRedraw property is set to False. The X1,
X2, Y1 and Y2 properties may be used to move
and resize the line at run-time. The three-letter
mnemonic for a Line is lin (eg. linDiagonal).
The following example positions a line on the
form from the top left corner to the bottom right
corner.
Private Sub Form_Load()
linDiagonal.X1 = 0 ' Top left
corner
34. DriveListBox Control
The DriveListBox allows the user to select a valid drive at run-
time. This control is usually synchronised with the DirListBox
and the FileListBox. The three-letter mnemonic for a
DriveListBox is drv (eg. drvList). The default event for a
DriveListBox is the Change event. As the drive may not be
ready to use, it is a good idea to use error trapping if
synchronised with the DirListBox and FileListBox.
DirListBox Control
The DirListBox displays a list of folders. This control is usually
synchronised with the DriveListBox and the FileListBox. The
three-letter mnemonic for a DirListBox is dir (eg. dirList). The
default event for a DirListBox is the Change event.
FileListBox Control
The FileListBox displays a list of files. This control is usually
synchronised with the DriveListBox and the DirListBox. The
three-letter mnemonic for a FileListBox is fil (eg. filList). The
default event for a filListBox is the Click event.
35. Property Description
Archive A boolean value to indicate whether archive
attributes are displayed (default: True).
Hidden A boolean value to indicate whether hidden
attributes are displayed (default: False).
Pattern A string that specifies the files to be displayed
(eg. *.html).
ReadOnl
y
A boolean value to indicate whether read-only
attributes are displayed (default: True)
System A boolean value to indicate whether system
attributes are displayed (default: False).
Multisele
ct
An integer value to indicate whether multiple selection is
allowed. The default is 0, meaning mutliselction is not allowed.
A value of 1 indicates simple multi-selection. Multiple items are
toggled on and off with a mouse click. A value of 2 indicates
36. DriveListBox, DirListBox, and FileListBox
Example
This example synchronises a DriveListBox, DirListBox and
FileListBox. To try the example, add a DriveListBox and name it
drvList, a DirListBox and name it dirList, and a FileListBox and
name it filList.
Private Sub dirList_Change()
filList.Path = dirList.Path
End Sub
Private Sub drvList_Change()
On Error GoTo driveError dirList.Path = drvList.Drive Exit
Sub driveError: MsgBox Err.Description, vbExclamation,
"Drive Error“
End Sub
Private Sub filList_Click()
Dim strFileName As String
strFileName = filList.List(filList.ListIndex) MsgBox
37. Shape Control
The Shape control is used to display a graphical shape. The
shape is set at design-time, and the actual shape is determined
by the Shape property and may be changed at run-time.
The Shape control is used to display a graphical shape. The
shape is set at design-time, and the actual shape is determined
by the Shape property and may be changed at run-time.
shpOutline.Shape = vbShapeOval
Properties :-
valu
e
constant Description
1 vbShapeRecta
ngle
Rectangle
2 vbShapeSquar
e
Square
3 vbShapeOval Oval
4 vbShapeCircle Circle