Beruflich Dokumente
Kultur Dokumente
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
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@.
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...
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...
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...
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
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
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)
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.
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.
objectname[(Index)].propertyname[(index)]
cmdOK.Caption
txtName.Text
Form Object
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.
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.
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.
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...
There are other types of operators that we will deal with later in the
course.
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
Sub cmdCalculate_Click ()
GrossPrice@ = Val(txtGrossPrice.Text)
txtNetPrice.Text = Str$(NetPrice@)
End Sub
Sub cmdClear_Click ()
txtGrossPrice.Text = “”
txtNetPrice.Text = “”
End Sub
Sub cmdQuit_Click ()
End
End Sub
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 ]