Sie sind auf Seite 1von 20

Visual Basic 5

Programming - 2
A Specialised Training Course
Contents
VARIABLES, CONSTANTS AND PROPERTY VALUES ............................................................... 2
Variables.................................................................................................................................. 2
Constants ................................................................................................................................. 3
Property Values ....................................................................................................................... 3
SCOPE AND DECLARATION OF VARIABLES.............................................................................. 4
Dim .......................................................................................................................................... 4
Global scope............................................................................................................................ 4
Form / Module level scope ...................................................................................................... 4
Procedural scope..................................................................................................................... 5
Static keyword ......................................................................................................................... 5
DATA TYPES ......................................................................................................................................... 5
Integers (%) ............................................................................................................................. 5
Long (&) .................................................................................................................................. 5
Single (!) .................................................................................................................................. 5
Double (#)................................................................................................................................ 6
Currency (@)........................................................................................................................... 6
String ($).................................................................................................................................. 6
Variant..................................................................................................................................... 6
FORMS & INITIAL CONTROLS ....................................................................................................... 7
Common Properties................................................................................................................. 7
Referencing Properties ............................................................................................................ 8
FORM OBJECT....................................................................................................................................... 8
CONTROL OBJECTS ............................................................................................................................... 9
Text Box ................................................................................................................................... 9
Label........................................................................................................................................ 9
Command Button ................................................................................................................... 10
List Box.................................................................................................................................. 10
Combo-box ............................................................................................................................ 11
Check Box.............................................................................................................................. 11
Frame .................................................................................................................................... 11
Option Button ........................................................................................................................ 12
NAMING CONVENTIONS ................................................................................................................ 13

PROGRAMMING IN VISUAL BASIC ............................................................................................. 14


Assignments ........................................................................................................................... 15
Arithmetic Operators ............................................................................................................. 16
EXERCISES.......................................................................................................................................... 17

Visual Basic Book 2 © Mark Collins 1999 Page 1


Variables, Constants and Property Values
Data contained in an application must be stored somewhere in memory
and be referenced by our BASIC code. The type of data stored (numbers,
text etc) is discussed in the next section. First we need to understand the
differences with the three kinds of data storage.

Variables

A variable is used for storing, as the name suggests, data that is likely to
change within our application. A variable is simply a space in memory to
store data of a certain type (see next section) to which we give a name.
There are rules that Visual Basic insists you adhere to when naming
variables...
• The first character must be a letter;
• Subsequent characters may be alphanumeric or an underscore;
• No punctuation marks except for the underscore, and the final
character may be a type declaration character (%, &, !, #, @ or $);
• Maximum of 40 characters;
• Do not use a reserved word without modification (e.g. vPrint rather
than print);
You should give your variables meaningful names. There is nothing to
stop you using a mix of upper and lowercase characters combining several
words (e.g. GrandTotal). Some language conventions (e.g Hungarian in
C) include an indicator of the data type first (e.g. intGrandTotal). In
BASIC however it is possible to use the type declaration character,
especially if there is no formal declaration of type (GrandTotal%).
Two similar variables with different type declaration characters may not
coexist in the same scope (see section on scope).
For example an application that takes input of a gross price, adds VAT
and outputs the net price needs variables to store the gross price and the
net price. As the application starts the prices are not stored, but space is
reserved for them as currency values and a name allocated (GrossPrice@
and NetPrice@). As the gross price is entered it is stored to the part of
memory referred to by GrossPrice@. A calculation follows involving
another value (VAT) and the result is stored in the other variable
NetPrice@.

Visual Basic Book 2 © Mark Collins 1999 Page 2


Constants

A constant is used for storing data that is not going to change during our
application. It is similar to a variable except the value can not change.
Constants are conventionally given uppercase names to help distinguish
them from variables and should be declared with the keyword Const.
Otherwise their name, type and scope attributes conform to the same rules
as variables.
It is best to show why we use constants by developing our previous
example. In our net to gross price calculation we would have used a
command to calculate the net price similar to...

GrossPrice@ = NetPrice@ * 1.175

However if the rate of VAT changed we would have to find the


occurrences of 1.175 in our code and replace them with the new figures.
A much more suitable method would be to declare a constant at the start
of our code similar to...

Const VAT! = 1.175

... and change our formula to...

GrossPrice@ = NetPrice@ * VAT

Now if the rate changes we only need to change the constant declaration at
the start of our code for all the formulae dependent on it to be updated.
Note that having used the type declaration character in our constant
declaration we do not need to use it thereafter.

Property Values

A lot of our data is going to be input and stored within the control objects
we use (text boxes to store a name for example). For most controls there is
what I call the Pertinent Data Property. In the case of a text box it is the
Text property, for an option button the Value property. Each property has
a type similar to variables. We are limited to storing a String of characters
in the Text property of a Text Box. We can however use data-conversion
to use text boxes for numeric entry too. These properties can be treated
similar to variables.
In our VAT calculation above we may have used a text box with the name
txtNetPrice to enter the net price. To store it in our variable we would
have used the following code...

NetPrice@ = Val( txtNetPrice.Text )

Visual Basic Book 2 © Mark Collins 1999 Page 3


Scope and Declaration of variables
Where variables and constants are declared determines where they can be
accessed. The different levels are…
• Global - available throughout application in all Forms and Modules;
• Form or Module - available to all procedures in a specific Form or
Module;
• Procedure (Local) - only available within that procedure.

Dim
A declaration statement uses the keyword Dim. The use of the As
keyword allows definition of data type ( rather than use the type
declaration character, if no type is specified it is of type Variant). For
example...

Dim Age% ‘Age as Integer (%)


Dim EmpName As String
Dim Salary As Currency

It is possible to not declare your variables and simply use the name in your
code. Whereas you can get away with this for small applications you
should get into the habit of making proper declarations (it also helps
convince ‘real’ programmers that you are using a ‘real’ language). It is
possible to force declarations in a project - recommended as many a
problem has been caused by mispelling one occurrence of a variable. It is
best to declare the variable type 'As Integer' than the equivalent % sign.

Global scope

To define a Global variable or constant it must be declared in the


declarations section of a module with the keyword Global. It may not be
declared in a form. For example...

Global Size As Integer ‘variable


Global Const VAT! = 1.175 ‘constant

Form / Module level scope

To define a form or module scoped variable or constant they should be


placed in the declarations section of that form or module and declared
using the Dim keyword. This is accessed by calling up the code window

Visual Basic Book 2 © Mark Collins 1999 Page 4


and selecting (general) in the Object combo-box and (declarations) in
the Proc combo-box.

Procedural scope

For now we’ll regard a procedure as a self contained block of code. The
code for each event for each object is a potential procedure and we can
also create our own. Variables or constants used only at procedure level
should be defined at the beginning of the procedure using the Dim
keyword. This makes them visible only to the procedure in which they are
declared and they go out of scope with the procedure.

Static keyword

Whenever a procedure is ended any procedurally scoped variables (local


variables) and their data are lost. If we want a variable to store data from
one instance of a procedure to the next we need to use the Static keyword.
These variables retain their value as long as the application is running. For
example...

Static Count as Integer

Data Types
In BASIC there are several base data-types available.

Integers (%)
2 bytes in size,
Range from -32768 to 32767

Long (&)
4 bytes in size,
Range from -2147,483,648 to 2147483648

Single (!)
4 Bytes in size, Range from
-3402823E38 to -1.401298E-45 for negative values,
0 (zero) and from 1.401298E-45 to 3402823E38 for positive values.
32-bits with sign (1 bit), exponent (8 bits) and mantissa (23 bits)

Visual Basic Book 2 © Mark Collins 1999 Page 5


Double (#)
8 Bytes in size, Range from
-1.79769313486232E308 to -4.94065645841247E-324 for negatives,
0 (zero) and from
4.94065645841247E-324 to 1.79769313486232E308 for positive values.
64-bits with sign (1 bit), exponent (11 bits) and mantissa (52 bits)

Currency (@)
8 Bytes in size, Range from
-922337203685477.5808 to 922337203685477.5808
with 4 fixed decimal places.
A 64-bit two’s complement integer scaled by 10,000 to give four decimal
places. Useful for precise calculations within the bounds of four decimal
places.

String ($)
Size = 1 byte per character
• Variable length - up to approx 65,500 characters
• Fixed length - of declared length up to 65K characters
The characters can be any of the 256 extended ASCII 8-bit characters.

Variant
If a variable is not explicitly declared it is made variant by default. It can
contain numeric, string or date data as well as special values Empty and
Null.
The variant is a very useful type but large and cumbersome when a more
specific type is available.

Visual Basic Book 2 © Mark Collins 1999 Page 6


Forms & initial Controls
We will concentrate on the main controls. For each control we shall
discuss the following...
• the important properties;
• the main events;

Common Properties

First let us look at some of the important properties that are common to
most objects.
Name: The object name used for referencing its properties or methods.
There is a convention to indicate in the name what type of object it is.
See the table later for details.
Caption: Determines what will appear on the form. For example a
command button caption is what appears in the button. Some input
objects (text-boxes, list boxes and combo-boxes) have a text property
instead.
Left, Top, Width & Height: These properties determine the relative
position and size of the object. The Left and Top properties determine
the top-left corner position relative to the parent object. For a form this
is relative to the screen, but for objects on a form this is relative to the
form. The Height and Width properties determine the size of the
object.
Enabled: Contains the values True or False. You may wish to disable
certain objects until certain conditions are met (e.g. an OK button
disabled while a text box is empty). By setting to False the control is
greyed out and disabled until the property is changed by the code.
Visible: Similar to Enabled except the control doesn’t appear at all when
False.
Font: There are various Font properties for controlling the appearance of
text in your objects. Be careful of using fonts that are not standard as
this could cause problems on other installations.
BackColor, FillColor, ForeColor: Used to change the colours of your
objects. Should be used sparingly as peoples colour selections for their
desktop may clash with your specific selections.

Visual Basic Book 2 © Mark Collins 1999 Page 7


Referencing Properties

To reference a property for a given object use the following syntax...

objectname[(Index)].propertyname[(index)]

ignore the optional index parts for now. For example...

cmdOK.Caption
txtName.Text

Form Object

We have already discussed what a form is - so let’s investigate its specific


important properties and methods.

Properties
BorderStyle: More than cosmetic, this determines whether the form can
be resized or not. The values 0 to 3 are valid with the following
meanings...
Value Style Effect
0 (none) No border, Control box, minimise or maximise
button. Can’t be moved, resized or minimised.
1 Fixed Single Can’t resize, but can maximise and minimise
2 Sizeable The default value - all resizing possible
3 Fixed Double No Maximise or Minimise buttons, nor can be
resized by dragging border. Can be
Max’d/Min’d/Restored via control box.

[There are two other values for Windows 95 toolbox styles.]

Caption: Specifically changes the Title Bar and iconized name.


Control Box: Can be removed from window at design time.
Min/Max Button: Can be removed from window at design time.
Icon: Selects an icon to use if the form is minimised. This can also be
chosen as the application icon for program manager. A file selection
dialog box appears for selecting a *.ICO file.
Mouse pointer: Allows you to select the mouse pointer shape when over
the form.
Visual Basic Book 2 © Mark Collins 1999 Page 8
Window State: The current state of the window...

Value Style
0 Normal
1 Minimised
2 Maximised

If you change the state at design time using the buttons, you can also
change it in your code.

Methods
Load / Unload: Not strictly methods, these are statements. In multi-form
applications these methods load and unload a form to and from
memory. This is not the same as showing and hiding.
Show / Hide: Once a form is loaded (see above) it can be shown or hidden
as required. If a form is not loaded the Show method will load it.

Events
Load: This event occurs when a form is loaded. The relevant procedure is
usually used to initialise or re-initialise variables on the form.

Control Objects
Text Box
Properties
MaxLength: Limits the size of text contained.
MultiLine: Determines the type of text-box.

Methods
None at this stage.

Events
Change: Occurs when text in a textbox is changed. The relevant procedure
could change the value of a variable or check that the box isn’t empty
to enable another control.

Label
Properties
Alignment: Selects left, right or centred text.
Visual Basic Book 2 © Mark Collins 1999 Page 9
Autosize: If True the control will automatically size itself to fit the
contained text.

Methods
None at this stage.

Events
Although it is possible to react to events created by this control it is
usually used simply for displaying static text on a form.

Command Button
Properties
Default: Usually one button on a form has this property set to True, which
means that it is the button to activate (cause a click event) if the user
presses the Enter key. Highlights the button with a darker border. Only
one default button can exist on a form, so changing the default button
using code sets the other buttons to false
Cancel: Similar to the Default, except activates button when Esc key
pressed (usually cancel).

Methods
None at this stage.
Events
Click: The most important event to react to is when the button is clicked.

List Box
Properties
Columns: It is possible to force declarations in a project - recommended.
Determines whether a list box scrolls vertically or horizontally. If it
scrolls horizontally determines how many columns are displayed.
List: A string array that contains the entries.
ListCount: The number of items in the list.
ListIndex: Determines the index of the currently selected item in the
control.
MultiSelect: Specifies whether a user can make multiple selections in a
file list box or list box and how the multiple selections can be made.
Selected: Determines the selection status of an item in a file list box or list
box. This property is an array of Boolean values with the same number
of items as the List property.
Sorted: Specifies whether the elements are automatically sorted
alphabetically.

Methods
AddItem: Adds a new item to a list box.

Visual Basic Book 2 © Mark Collins 1999 Page 10


RemoveItem: Removes an item from a list box

Events
Although a lot of activity occurs in a list box it is not usual to react to an
event at the list box. You usually act on the selected items when a related
command button is clicked.

Combo-box
A combo box combines the main properties and methods of a list-box
with the additional flexibility of a text box and so will use the Change
event like a text box. An important unique feature is the following
property.
Style: Specifies the type of combo box and the behaviour of its list box
portion as follows...

Value Effect
0 (Default) Dropdown Combo. Includes a drop-down list and an edit
area. The user can select from the list or type in the edit area.
1 Simple Combo. Includes an edit area and a list that is always
displayed. The user can select from the list or type in the edit area.
The size of a Simple Combo box includes both the edit and list
portions. By default, a Simple Combo box is sized so that none of
the list shows. Increase the Height property to show more of the
list.
2 Dropdown List. This style only allows selection from the drop-
down list.

Check Box
Properties
Value: As well as storing the Boolean Yes/No, true/false input it can be set
by code to Determine the state. 0 is Unchecked (default), 1 is Checked,
and 2 is Greyed (dimmed - similar to enabled = False).

Methods
No specific methods.

Events
Click: This event shows that the value has changed, you may want your
application to respond immediately or wait until a command button is
clicked before responding to its value.

Frame
This control is not usually manipulated or changed except to alter the
Caption. Its use is to group Option buttons or other controls.
Visual Basic Book 2 © Mark Collins 1999 Page 11
Option Button
Properties
Value: Each option button in a group can have the value of 0 or 1 where 1
means that option is selected. Only one in a group may be selected so
by selecting a button the previously selected button is deselected.

Methods
No specific methods.

Events
Click: As CheckBox click event.

Visual Basic Book 2 © Mark Collins 1999 Page 12


Naming conventions
When you use a form or control you should give it a meaningful name,
otherwise you end up with a collection of obscure objects (Form1,
Command4, Check3, List1 etc.). It is conventional to prefix the name
with a type code, for example frmMain or txtName. The following table
lists the prefix to use...

Object Prefix Example


Form frm frmMain
Text Box txt txtName
Label lbl lblName
Command Button cmd cmdOK
Check Box chk chkBold
Option Button opt optSmall
List Box lst lstUsers
Combo Box cbo cboEmployees
Frame fra fraSizes
Picture box pic picPhoto
Horizontal Scroll Bar hsb hsbQuantity
Vertical Scroll Bar vsb vsbQuantity
Timer tmr tmrAlarm
Drive List Box drv drvLocal
Directory list Box dir dirLocal
File List Box fil filLocal
Shape shp shpBox
Line lin linTitle
Image img imgPhoto
Data dta dtaStudents
Grid grd grdBudget
OLE ole oleSheet

Although Microsoft advocate the above naming conventions,


unfortunately the automatic creation of new controls default names within
a project become form1, list1, list2, etc. and finding the appropriate
control will be becomes increasingly difficult.

NB. Using the 3 prefix lettering convention allows easy identification of


the type of control when reading the code and it also allows easy
navigation to the type of control via the properties window pull down list
box by alphabetically listing the prefix types together.

Visual Basic Book 2 © Mark Collins 1999 Page 13


Programming in Visual Basic
Now we have our building blocks of forms, controls and data (variables
and constants) we can begin to manipulate them using code. Although it
is possible to edit our code using conventional text editors it is much
simpler in Visual Basic to use the Code Window.

Figure 1 - the Code Window

The code window can show either a single procedure or several


procedures at a time.
The picture above shows the code window of a future exercise and shows
the skeleton of two procedures. The first is the form procedure and code
here is usually intended to invoke specific effects such as hot-spots on
Internet pages. The code in the second procedure has been removed given
that this is a future exercise but the name of the procedure should give you
a clue as to what might happen if the mouse cursor is clicked over this
particular image.
The first and last lines that define the procedure are automatically seeded
(created and named for you since they generally relate to specific VB
objects) but the code in-between is where we get involved.
The Code window is usually invoked by double clicking a form or control
that brings up the main event procedure for that object. Once it is there we
can use the object combo-box (on the left) to select a different object and
the proc combo box (on the right) to select the specific (event) procedure.

Visual Basic Book 2 © Mark Collins 1999 Page 14


Assignments

A lot of our initial code will involve assigning a value to a variable or


property. To do this you use the = operator. An operator is simply a
symbol that has special meaning to BASIC. The Let Statement assigns the
value of an expression to a variable using the following syntax...

[Let] variable = valueexpression

The reserved word Let is always optional. In fact, most Basic


programmers never use the Let reserved word. Here are some examples

Value = 39.34
cmdOK.Enabled = False

A value expression can be assigned to a variable only if the data types they
have are compatible. The main type conversions that we will require early
on are between String and Numeric and vice-versa to allow entry of
numeric information via text boxes.
To use a number entered into a text box as a string like a number we use
the Val( ) conversion function as follows...

GrossPrice@ = Val( txtGrossPrice.Text )

To present a number in a label, text box or other string property we need


to use the Str$( ) function as follows...

lblNetprice.Caption = “£” & Str$( NetPrice@ )

Note that in the last example we have also performed a concatenation of


strings using the pound sign in quotes (a string literal) and the string
produced by the Str$( ) function using the & operator. This is the operator
for joining strings (you can use ‘+’, but ‘&’ is safer) as variant variables
could be misinterpreted to do an addition rather than a string
concatenation operation.

Visual Basic Book 2 © Mark Collins 1999 Page 15


Arithmetic Operators

The following Arithmetic operators are used by Visual Basic...

Symbol Main use Example


+ to sum two numbers Value1 = Value2 + Value3
- find the difference of two numbers Value1 = Value2 - Value3
indicate negative value Let Value4 = -67

* to multiply two numbers Value1 = Value2 * Value3


/ to divide one number by another Value1 = Value2 / Value3
^ To raise a number by the power of an Value1 = Value2 ^ 2
exponent
Mod Returns the remainder from a division Value1 = Value2 Mod Value3

There are other types of operators that we will deal with later in the
course.

Visual Basic Book 2 © Mark Collins 1999 Page 16


Exercises
Preparation
Create subdirectories in your F:\PROJECT directory called...
• VAT
• CELSIUS

Exercise 1

If you have just started Visual Basic you will have a Blank new project,
otherwise start a New Project saving your previous work if necessary.

1 Edit your form so it looks like the following picture. Give the
following objects the names and text/captions shown in the table

Type Name Caption / Text Other...


Form frmVAT VAT Calculator
Label lblGross Gross Price £
lblNet Net Price £
Command cmdCalculate Calculate Default = True
Button
cmdQuit Quit Cancel = True
cmdClear Clear Screens Default =False
Text Box txtGrossPrice blank
Text Box txtNetPrice blank

2 Enter the following in the (general)/(declarations) code box

Const VAT! = 1.175

Visual Basic Book 2 © Mark Collins 1999 Page 17


3 Modify the relevant event procedure for each of the following events...

Sub cmdCalculate_Click ()

GrossPrice@ = Val(txtGrossPrice.Text)

NetPrice@ = GrossPrice@ * VAT

txtNetPrice.Text = Str$(NetPrice@)

End Sub

Sub cmdClear_Click ()

txtGrossPrice.Text = “”
txtNetPrice.Text = “”

End Sub

Sub cmdQuit_Click ()

End

End Sub

4 Save the form as FRMVAT.FRM and your project as VAT.VBP in


the VAT directory you prepared earlier.
5 Run the application, entering numeric data into the text box and
pressing the enter key?
6 What happens if you turn off the default property on the Calculate
button?
7 What happens if you turn on the default property on the Clear screens
button?
8 What happens if you alter the values of the MaxLength and Locked
attributes of the text boxes properties?

Exercise 2
Create a similar project called CELSIUS.VBP which converts between
Fahrenheit and Centigrade. The structure will be similar to the VAT
application.
[ Note: Centigrade = (Fahrenheit-32) * 5 / 9 ]
[ Fahrenheit = (Centigrade * 9/5) + 32 ]

Visual Basic Book 2 © Mark Collins 1999 Page 18


Exercise 3
Add a check box (or if ambitious, option buttons) to determine which way
the conversion is to work (C to F, or F to C) in your CELSIUS application.
The calculate button then needs to confirm which formula to use by
referring to the added control.
What other improvements can you make?

Visual Basic Book 2 © Mark Collins 1999 Page 19

Das könnte Ihnen auch gefallen