visual basic 5-6 course part 2

20
 Visual Basic 5 Programming - 2  A Specialised T raining Course

Upload: mark-collins

Post on 30-May-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 1/20

 

Visual Basic 5Programming - 2

 A Specialised Training Course

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 2/20

Visual Basic Book 2 © Mark Collins 1999 Page 1

Contents

VARIABLES, CONSTANTS AND PROPERTY VALUES ..................................................... .......... 2

Variables................................................... ........................................................... .................... 2

Constants .................................................. ........................................................... .................... 3Property 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 (&) ................................................... ........................................................... .................... 5Single (!) ................................................... ............................................................ ................... 5

  Double (#)....................................... ............................................................ ............................. 6 

Currency (@)............... ........................................................... ................................................. 6 

String ($)............................... ............................................................ ....................................... 6 

Variant...................................................... ............................................................ ................... 6 

FORMS & INITIAL CONTROLS ...................................................... ................................................. 7

Common Properties...................................................... ........................................................... 7 

  Referencing Properties ........................................................... ................................................. 8

FORM OBJECT........................................................ ........................................................... .................... 8CONTROL OBJECTS.......................................................... ........................................................... .......... 9

Text Box .................................................... ........................................................... .................... 9

 Label......................................................... ........................................................... .................... 9Command 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

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 3/20

Visual Basic Book 2 © Mark Collins 1999 Page 2

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 thedifferences with the three kinds of data storage.

Variables 

A variable is used for storing, as the name suggests, data that is likely tochange 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 namingvariables...

•  The first character must be a letter;

•  Subsequent characters may be alphanumeric or an underscore;

•  No punctuation marks except for the underscore, and the finalcharacter may be a type declaration character (%, &, !, #, @ or $);

•  Maximum of 40 characters;

•  Do not use a reserved word without modification (e.g. vPrint ratherthan print);

You should give your variables meaningful names. There is nothing tostop 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). InBASIC 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 VATand 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 isreserved 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 involvinganother value (VAT) and the result is stored in the other variable

NetPrice@. 

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 4/20

Visual Basic Book 2 © Mark Collins 1999 Page 3

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 rulesas variables.

It is best to show why we use constants by developing our previousexample. 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 theoccurrences 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 startof 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 constantdeclaration 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 iswhat I call the Pertinent Data Property. In the case of a text box it is theText property, for an option button the Value property. Each property has

a type similar to variables. We are limited to storing a String of charactersin the Text property of a Text Box. We can however use data-conversionto 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 nametxtNetPrice to enter the net price. To store it in our variable we would

have used the following code...

NetPrice@ = Val( txtNetPrice.Text )

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 5/20

Visual Basic Book 2 © Mark Collins 1999 Page 4

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 orModule;

•  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). Forexample...

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 youshould get into the habit of making proper declarations (it also helps

convince ‘real’ programmers that you are using a ‘real’ language). It ispossible to force declarations in a project - recommended as many aproblem has been caused by mispelling one occurrence of a variable. It isbest 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 bedeclared 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 beplaced in the declarations section of that form or module and declaredusing the Dim keyword. This is accessed by calling up the code window

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 6/20

Visual Basic Book 2 © Mark Collins 1999 Page 5

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

Procedural scope 

For now we’ll regard a procedure as a self contained block of code. Thecode for each event for each object is a potential procedure and we canalso 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 aredeclared 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 fromone 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. Forexample...

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

-3402823 E38 to -1.401298 E-45 for negative values,

0 (zero) and from 1.401298 E-45 to 3402823 E38 for positive values.

32-bits with sign (1 bit), exponent (8 bits) and mantissa (23 bits)

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 7/20

Visual Basic Book 2 © Mark Collins 1999 Page 6

Double (#) 8 Bytes in size, Range from

-1.79769313486232 E308 to -4.94065645841247 E-324 for negatives,

0 (zero) and from

4.94065645841247 E-324 to 1.79769313486232 E308 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 decimalplaces.

String ($) Size = 1 byte per character

•  Variable length - up to approx 65,500 characters

  Fixed length - of declared length up to 65K charactersThe 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 morespecific type is available.

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 8/20

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 9/20

Visual Basic Book 2 © Mark Collins 1999 Page 8

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 specificimportant properties and methods.

 Properties

BorderStyle: More than cosmetic, this determines whether the form canbe 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 maximisebutton. 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 beresized 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 selectiondialog box appears for selecting a *.ICO file.

Mouse pointer: Allows you to select the mouse pointer shape when overthe form.

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 10/20

Visual Basic Book 2 © Mark Collins 1999 Page 9

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 alsochange it in your code.

 Methods

Load / Unload:  Not strictly methods, these are statements. In multi-formapplications 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 hiddenas 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 isusually 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.

 MethodsNone at this stage.

 Events

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

Label 

 Properties

Alignment: Selects left, right or centred text.

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 11/20

Visual Basic Book 2 © Mark Collins 1999 Page 10

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 isusually 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 userpresses the Enter key. Highlights the button with a darker border. Only

one default button can exist on a form, so changing the default buttonusing 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 listbox. 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.

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 12/20

Visual Basic Book 2 © Mark Collins 1999 Page 11

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 relatedcommand button is clicked.

Combo-box A combo box combines the main properties and methods of a list-boxwith the additional flexibility of a text box and so will use the Change

event like a text box. An important unique feature is the followingproperty.

Style: Specifies the type of combo box and the behaviour of its list boxportion as follows...

Value Effect

0 (Default) Dropdown Combo. Includes a drop-down list and an editarea. 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 alwaysdisplayed. 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 thelist.

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 setby 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 yourapplication to respond immediately or wait until a command button isclicked before responding to its value.

Frame 

This control is not usually manipulated or changed except to alter theCaption. Its use is to group Option buttons or other controls.

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 13/20

Visual Basic Book 2 © Mark Collins 1999 Page 12

Option Button 

 Properties

Value: Each option button in a group can have the value of 0 or 1 where 1means 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.

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 14/20

Visual Basic Book 2 © Mark Collins 1999 Page 13

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 tablelists 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 drvLocalDirectory 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 appropriatecontrol 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 listbox by alphabetically listing the prefix types together.

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 15/20

Visual Basic Book 2 © Mark Collins 1999 Page 14

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 itis possible to edit our code using conventional text editors it is muchsimpler in Visual Basic to use the Code Window.

Figure 1 - the Code Window

The code window can show either a single procedure or severalprocedures 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 codehere is usually intended to invoke specific effects such as hot-spots onInternet 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 youa clue as to what might happen if the mouse cursor is clicked over thisparticular image.

The first and last lines that define the procedure are automatically seeded

(created and named for you since they generally relate to specific VBobjects) 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 wecan use the object combo-box (on the left) to select a different object andthe proc combo box (on the right) to select the specific (event) procedure.

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 16/20

Visual Basic Book 2 © Mark Collins 1999 Page 15

Assignments 

A lot of our initial code will involve assigning a value to a variable orproperty. To do this you use the = operator. An operator is simply asymbol 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 theyhave 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 operatorfor joining strings (you can use ‘+’, but ‘&’ is safer) as variant variables

could be misinterpreted to do an addition rather than a stringconcatenation operation.

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 17/20

Visual Basic Book 2 © Mark Collins 1999 Page 16

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

indicate negative value

Value1 = Value2 - Value3

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

exponent

Value1 = Value2 ^ 2

Mod Returns the remainder from a division Value1 = Value2 Mod Value3

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

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 18/20

Visual Basic Book 2 © Mark Collins 1999 Page 17

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 thefollowing 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 £

CommandButton

cmdCalculate Calculate Default = True

cmdQuit Quit Cancel = TruecmdClear 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

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 19/20

Visual Basic Book 2 © Mark Collins 1999 Page 18

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 inthe VAT directory you prepared earlier.

5 Run the application, entering numeric data into the text box andpressing 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 screensbutton?

8 What happens if you alter the values of the MaxLength and Lockedattributes of the text boxes properties?

Exercise 2

Create a similar project called CELSIUS.VBP which converts betweenFahrenheit and Centigrade. The structure will be similar to the VATapplication.

[ Note: Centigrade = (Fahrenheit-32) * 5 / 9 ]

[ Fahrenheit = (Centigrade * 9/5) + 32 ]

8/9/2019 Visual Basic 5-6 Course Part 2

http://slidepdf.com/reader/full/visual-basic-5-6-course-part-2 20/20

Visual Basic Book 2 © Mark Collins 1999 Page 19

Exercise 3

Add a check box (or if ambitious, option buttons) to determine which waythe 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 byreferring to the added control.

What other improvements can you make?