PROGRAMMING IN

Document Sample
PROGRAMMING IN Powered By Docstoc
					Information Technology Studies

Programming in Visual Basic for Windows

CONTENTS

1. LOOKING AT WINDOWS ............................................................................................................................................ 4 HISTORY OF WINDOWS AND VB ........................................................................................................................................ 4 ABOUT WINDOWS ............................................................................................................................................................. 6 2. LOOKING AT VISUAL BASIC .................................................................................................................................... 7 ABOUT VISUAL BASIC ........................................................................................................................................................ 7 WINDOWS EVENTS ............................................................................................................................................................. 7 VB EVENTS (SUMMARY) ................................................................................................................................................... 8 DEVELOPING A VB APPLICATION ....................................................................................................................................... 9 RUNNING A VB APPLICATION ............................................................................................................................................ 9 IMPORTANT EVENTS FOR THIS SUBJECT ........................................................................................................................... 10 THE VB ENVIRONMENT ................................................................................................................................................... 10 STUDENT NOTES (TOPICS 1 AND 2) .................................................................................................................................. 11 3. VB EVENTS ................................................................................................................................................................... 12 VB EVENTS (REVISITED) ................................................................................................................................................. 12 EVENT HANDLING MODULES ........................................................................................................................................... 12 FORM LOADING EVENTS .................................................................................................................................................. 13 EVENT MONITORING ........................................................................................................................................................ 13 4. VB CONTROLS ............................................................................................................................................................ 13 MAJOR CONTROLS WE WILL WORK WITH IN VB ............................................................................................................... 14 TED EXAMPLE ................................................................................................................................................................ 15 CONTROL ARRAYS ........................................................................................................................................................... 16 ACCESS KEYS .................................................................................................................................................................. 16 5. DATA TYPES AND DATA HOLDERS ...................................................................................................................... 17 DATA REFERENCES .......................................................................................................................................................... 17 DATA HOLDERS ............................................................................................................................................................... 17 USING VARIABLES ........................................................................................................................................................... 18 USING CONSTANTS .......................................................................................................................................................... 20 INTRODUCTION TO ARRAYS ............................................................................................................................................. 21 INTRODUCTION TO RECORDS ........................................................................................................................................... 21 STUDENT NOTES (TOPICS 3, 4 AND 5) .............................................................................................................................. 23 6. OPERATORS................................................................................................................................................................. 24 ARITHMETIC OPERATORS ................................................................................................................................................. 24 STRING OPERATORS ......................................................................................................................................................... 24 RELATIONAL OPERATORS ................................................................................................................................................ 24 LOGICAL OPERATORS ...................................................................................................................................................... 25 OPERATOR PRECEDENCE ................................................................................................................................................. 25 7. VISUAL BASIC PROJECTS........................................................................................................................................ 26 FORMS ............................................................................................................................................................................. 26 TEXT BOXES .................................................................................................................................................................... 29 COMMON DIALOG CONTROL ............................................................................................................................................ 30 THE .VBP FILE ................................................................................................................................................................ 31 STUDENT NOTES (TOPICS 6 AND 7) .................................................................................................................................. 32

b0688454-8000-4686-aa20-1e43dba5c849.doc

1

Information Technology Studies

Programming in Visual Basic for Windows

CONTENTS (cont.)

8. SEQUENCE STATEMENTS........................................................................................................................................ 33 9. SELECTION STRUCTURES ....................................................................................................................................... 34 THE IF STATEMENT .......................................................................................................................................................... 34 BOOLEAN EXPRESSIONS ................................................................................................................................................... 37 THE CASE STATEMENT .................................................................................................................................................... 38 10. ITERATION STRUCTURES (LOOPING) ............................................................................................................... 39 FOR - NEXT STRUCTURE .................................................................................................................................................. 40 DO - LOOP STRUCTURE .................................................................................................................................................... 42 FOR EACH - NEXT STRUCTURE ........................................................................................................................................ 44 STUDENT NOTES (TOPICS 8, 9 AND 10) ............................................................................................................................ 46 11. VARIABLE AND PROCEDURE SCOPE................................................................................................................. 47 12. DEBUGGING ............................................................................................................................................................... 49 BREAK MODE .................................................................................................................................................................. 49 DEBUGGING FEATURES .................................................................................................................................................... 50 STUDENT NOTES (TOPICS 11 AND 12) .............................................................................................................................. 51 13. PROCEDURES ............................................................................................................................................................ 52 DIVIDE AND CONQUER ..................................................................................................................................................... 52 SUB PROCEDURES ............................................................................................................................................................ 53 USER-DEFINED FUNCTIONS.............................................................................................................................................. 53 PASSING PARAMETERS ..................................................................................................................................................... 54 COHESION AND COUPLING ............................................................................................................................................... 54 STUDENT NOTES (TOPIC 13) ............................................................................................................................................ 57 14. DATA MANIPULATION ........................................................................................................................................... 58 WORKING WITH NUMBERS ............................................................................................................................................... 58 WORKING WITH STRINGS ................................................................................................................................................. 63 STUDENT NOTES (TOPIC 14) ............................................................................................................................................ 66 15. USING DATA FILES .................................................................................................................................................. 67 TYPES OF FILES ................................................................................................................................................................ 67 MANIPULATING DATA FILES ............................................................................................................................................ 68 SEQUENTIAL FILES ........................................................................................................................................................... 69 RANDOM-ACCESS FILES .................................................................................................................................................. 76 BINARY FILES .................................................................................................................................................................. 81 STUDENT NOTES (TOPIC 15) ............................................................................................................................................ 83 16. ARRAYS ....................................................................................................................................................................... 84 ARRAY SYNTAX ............................................................................................................................................................... 84 WORKING WITH ARRAYS ................................................................................................................................................. 84 SCOPE OF ARRAY DECLARATIONS ................................................................................................................................... 85 USING TWO-DIMENSIONAL ARRAYS ................................................................................................................................ 88 ARRAY FUNCTIONS .......................................................................................................................................................... 89 ARRAYS - FIXED (STATIC) AND DYNAMIC MEMORY ALLOCATION .................................................................................. 90 PASSING ARRAYS TO PROCEDURES .................................................................................................................................. 91

b0688454-8000-4686-aa20-1e43dba5c849.doc

2

Information Technology Studies

Programming in Visual Basic for Windows

CONTENTS (cont.)

17. USING RECORDS ...................................................................................................................................................... 92 STUDENT NOTES (TOPICS 16 AND 17) .............................................................................................................................. 99 18. WORKING WITH FILES ........................................................................................................................................ 100 FILE AND DIRECTORY MANAGEMENT FUNCTIONS ......................................................................................................... 100 COMMON DIALOG CONTROL (REVISITED) ...................................................................................................................... 102 DATA VALIDATION......................................................................................................................................................... 103 STUDENT NOTES (TOPIC 18) .......................................................................................................................................... 104 19. PROGRAM ERRORS ............................................................................................................................................... 105 SYNTAX ERRORS............................................................................................................................................................ 105 RUN-TIME ERRORS ........................................................................................................................................................ 105 LOGIC ERRORS ............................................................................................................................................................... 106 ERROR HANDLING ......................................................................................................................................................... 107 20. SYSTEM OBJECTS .................................................................................................................................................. 110 THE APP OBJECT............................................................................................................................................................ 110 DEBUG OBJECT .............................................................................................................................................................. 110 CLIPBOARD OBJECT ....................................................................................................................................................... 111 PRINTER OBJECT ............................................................................................................................................................ 111 SCREEN OBJECT ............................................................................................................................................................. 112 STUDENT NOTES (TOPICS 19 AND 20) ............................................................................................................................ 113 APPENDIX ....................................................................................................................................................................... 114 VB NAMING CONVENTIONS ........................................................................................................................................... 114

b0688454-8000-4686-aa20-1e43dba5c849.doc

3

Information Technology Studies

Programming in Visual Basic for Windows

1. LOOKING AT WINDOWS Windows applications share: 1. 2. 3. 4. Common Graphical User Interface, GUI, (tab, point-and-click etc.) Share same hardware (monitors, printers, disk drives etc.) Share same CPU (multi-tasking, event-driven, DDE, OLE, ActiveX etc.) Consistent look and feel (windows, menubars, toolbars, dialog boxes, help etc.)

History of Windows and VB Windows V1 Windows V2  1985 1987

Applications developed in C - difficult - time consuming - hard to debug - Microsoft SDK complex (>600 functions) 1990 1995 1998 2000 (incorporating Windows NT technology)

Windows V3 Windows 95 Windows 98 Windows 2000 

Applications could now be developed in Visual Basic (from Windows V3 onwards) VB VB VB VB VB VB VB V1 V2 V3 V4 V5 V6 V7 1991 1992 1993 1995 1997 1998 ????

(16 bit or 32 bit) (32 bit version)

- language easy to master (derived form BASIC) - applications written in a fraction of the time - fun to use (screen design etc.) - fewer bugs and easier to find and fix (excellent debugging tools) - small performance penalty (event monitoring)

b0688454-8000-4686-aa20-1e43dba5c849.doc

4

Information Technology Studies

Programming in Visual Basic for Windows

1. Looking at Windows (cont.) Windows API Application programs, like the kind of programs developed with languages such as Visual Basic, must be developed to work with a specific operating system. Application programs interact with operating systems by using operating system functions designed for application developers to exploit. These functions are usually referred to as the Application Programming Interface (API). These API functions enable programmers to add such functionality to their programs as opening and saving files, checking system hardware, using the computer‟s internal clock, and - in the Windows family of operating systems - creating, modifying, and communicating with Windows.

VB Applications

API Funcions

DLL's

VBX's

WIN Applications VB (70% of API) USER.DLL GUI -mouse -windows Excell Access Word Visual C++

Windows API ~ 750+ functions KERNEL.DLL GDI.DLL Device drivers Print manager Memory manager OLE, DDE ActiveX etc

Operating System
Microsoft Office Visual Basic, apart from being a stand-alone programming language for developing Windows applications, is also the scripting (macro programming) language for nearly the entire suite of Microsoft desktop applications, including Word, Excel, Access and PowerPoint. Applications of the Microsoft Office suite, through hierarchical object models, expose their functionality for use by Visual Basic applications. ActiveX The existing technology of object linking and embedding (OLE) is being superseded by ActiveX. The name of ActiveX was introduced when Microsoft resolved to pursue Internet development. What then followed was a definition of Internet standards and technology for cross-platform distributed computing within an enterprise (intranets). ActiveX makes minor modifications to preexisting OLE technology in pursuit of smaller, more quickly downloadable components in Internet and intranet applications.

b0688454-8000-4686-aa20-1e43dba5c849.doc

5

Information Technology Studies

Programming in Visual Basic for Windows

1. Looking at Windows (cont.) About Windows Parts of a Window

  

title bar min / max buttons tool bars

  

borders close button scroll box / bars

  

control-menu box menu bar icons

Parts of an Application

 window

frames



title bars

 menu

bar

 tool

bars

scroll

bars

 status

bar

b0688454-8000-4686-aa20-1e43dba5c849.doc

6

Information Technology Studies

Programming in Visual Basic for Windows

2. LOOKING AT VISUAL BASIC About Visual Basic VB6 Opening Screen

  

menu window project window form window

  

toolbar window properties window code window (hidden)

 

toolbox window form layout window

(windows may be docked or free floating – see menu Tools…Options…Docking)

Windows Events
 

An event is an action that triggers the execution of code Events can come from several sources: Source user computer program another program Examples mouse click, pressing a key etc. specified time period elapses explicitly activate an event request data exchange

b0688454-8000-4686-aa20-1e43dba5c849.doc

7

Information Technology Studies

Programming in Visual Basic for Windows

2. Looking at Visual Basic (cont.) VB Events (Summary) For this subject :    Events in bold italic you will use Events in italic you may use The rest you will probably not use KeyPress KeyUp LinkClose LinkError LinkExecute LinkNotify LinkOpen Load LostFocus MouseDown MouseMove MouseUp ObjectMove Paint PathChange PatternChange QueryUnload Reposition RequestChangeFileName (Add-In) RequestWriteFile (Add-In) Resize RowColChange RowLoaded RowResize Scroll SelChange Terminate Timer UnboundAddData UnboundDeleteRow UnboundReadData UnboundWriteData UnCheckOut (Add-In) Unload Updated Validate

Activate AfterAddFile (Add-In) AfterChangeFileName (Add-In) AfterCloseFile (Add-In) AfterColUpdate AfterDelete AfterInsert AfterNewProject (Add-In) AfterRemoveFile (Add-In) AfterUpdate AfterWriteFile (Add-In) BeforeColUpdate BeforeDelete BeforeInsert BeforeLoadFile (Add-In) BeforeUpdate Change CheckIn (Add-In) CheckOut (Add-In) Click ColResize ConnectAddIn (Add-In) DblClick Deactivate DisconnectAddIn (Add-In) DoGetAddFileName (Add-In) DoGetNewFileName (Add-In) DoGetOpenProjectName (Add-In) DragDrop DragOver DropDown Error Fetch (Add-In) GotFocus HeadClick Initialize KeyDown 2. Looking at Visual Basic (cont.)
b0688454-8000-4686-aa20-1e43dba5c849.doc

8

Information Technology Studies

Programming in Visual Basic for Windows

Developing a VB Application 1. 2. 3. 4. 5. 6. Define the problem (Program Specification etc.). Draw the objects that make up the user interface (forms). Set the properties for each object (change appearance and behaviour). Decide what events the objects (controls) on the form (window) should respond to. Write (code) the event procedures for those events. Write any procedures that the event procedures may need for their job (modularise).

NOTE: You do not need to write any code for the first four steps. Running a VB Application 1. 2. 3. 4. Focus    The object on the interface that will receive the next piece of input. For mouse input, the focus always coincides with the pointer (button down) location. For keyboard input, the focus depends on the context. VB monitors all objects in each window for ALL events possible for each object. When an event is detected, VB checks to see if any code is written for that event for that object. If there is any code behind the event VB will execute it (run the code). Back to Step 1 (until program terminates).

 In text, the focus is shown by an insertion point (where newly typed characters will be inserted).  In menus and dialogue box controls, the focus is shown by an active control indicator. The active control indicator can be: - an insertion point, - highlighting, or - a dotted box. Navigation The user can move the input focus by navigating on the screen. Navigation can be done using the mouse (point and click) or the keyboard (Tab Key).

b0688454-8000-4686-aa20-1e43dba5c849.doc

9

Information Technology Studies

Programming in Visual Basic for Windows

2. Looking at Visual Basic (cont.) Providing Feedback Applications should keep the user informed about the current state of the application by providing feedback. The user should be in control of the application, not the reverse! eg.
    

Inform the user that a particular mode has been entered (eg. hourglass) acknowledge a command (eg. Message Box: “Do you wish to delete?”) point out an error (eg. trap errors and give appropriate error messages) track the progress of an operation (eg. status bars / indicators bars etc.) and so on.…

Visual (either graphical or textual) feedback, is the most common, but auditory feedback is also useful (eg. Beep!!).

Important Events for this Subject There are 4 events that you will definitely have to work with in this subject : Event Name Click Change Load KeyPress The TED example given to you will demonstrate some of these events (more later)

The VB Environment Walkthrough - look at VB professional edition:
menu toolbar toolbox form project properties code

Run some VB sample applications from the VB/Samples directory on the student network. Examine the code in the applications and in particular the EVENTS that the code responds to.

b0688454-8000-4686-aa20-1e43dba5c849.doc

10

Information Technology Studies

Programming in Visual Basic for Windows

Student Notes (Topics 1 and 2)

b0688454-8000-4686-aa20-1e43dba5c849.doc

11

Information Technology Studies

Programming in Visual Basic for Windows

3. VB EVENTS VB Events (Revisited) For this subject :   Click Change Load KeyPress Events in bold italic you will use (left column) Events in italic you may use (right column) GotFocus LostFocus Scroll Unload

Event Handling Modules We have controls (objects) and events. VB provides a procedure for every event of a control. Sub Control_Event ( ) ... ... End Sub eg. Sub txtTed_Click ( ) ... ... End Sub Sub txtTed_Change ( ) ... ... End Sub „Control : TextBox „Event : Click

„Control : TextBox „Event : Change

Certain objects will recognise certain events. For example, event handling procedures can be written for all of the following events that a text box will recognise : Change Event Click Event DblClick Event DragDrop Event DragOver Event GotFocus Event KeyDown Event KeyPress Event KeyUp Event LinkClose Event LinkError Event LinkNotify Event LinkOpen Event LostFocus Event MouseDown Event MouseMove Event MouseUp Event

3. VB Events (cont.)
b0688454-8000-4686-aa20-1e43dba5c849.doc

12

Information Technology Studies

Programming in Visual Basic for Windows

Event Monitoring
System queue
(all applications)
WM_MOUSEMOVE

Application queue
(each application)
WM_MOUSEMOVE

event

decide which app queue

mouse m ove

Form Loading Events A series of events can occur when the user, or program, takes some action. For example, when a form is first loaded into memory and shown on the screen the following events occur :
     

Form_Initialize (instance creation) Form_Load (into memory) Form_Activate (onto the screen) Form_Resize (resize window) Form_GotFocus (only if the form can have focus) Form_Paint & .AutoRedraw property (redraw window)

The Form_Load Event
 

When VB loads a form into memory one of the events it generates is a Form_Load event Ideal for initialisation code / set up routines etc. eg. Sub Form_Load() txtTed.Text = "" 'clear the text box Call BlankText 'call user-defined procedure txtTed.FontBold = False txtTed.FontItalic = False txtTed.FontUnderline = False 'with txtTed 'could also be written as ' .FontBold = False ' .FontItalic = False ' .FontUnderline = False 'end with

chkBold.Value = vbUnchecked chkItalic.Value = vbUnchecked chkUnderline.Value = vbUnchecked End Sub 4. VB CONTROLS
b0688454-8000-4686-aa20-1e43dba5c849.doc

'constant = 0

13

Information Technology Studies

Programming in Visual Basic for Windows

Definition :

A Control is an object attached to a window.

Major Controls we will work with in VB 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. Form TextBox CommandButton Label ListBox ComboBox OptionButton (radio button) CheckBox Frame ScrollBar PictureBox ImageBox Common Dialog Control

VB Controls (objects) are found in the ToolBox. Each VB Control has associated with it:
    

control type name properties events methods

eg. Label, CommandButton, TextBox eg. Label1, cmdOK, txtLastName eg. Caption, FontSize, BackColor eg. Click, DblClick, LostFocus eg. SetFocus, AddItem, Cls

Note :
 

Controls and their properties can be created either at design time or run time. Some properties can only be set at run time (eg. the TextBox properties of SelText, SelLength and SelStart) at run time : Setting Properties object.property = value Invoking methods object.method eg. txtLastName.Text = FileName eg. txtLastName.SetFocus

b0688454-8000-4686-aa20-1e43dba5c849.doc

14

Information Technology Studies

Programming in Visual Basic for Windows

4. VB Controls (cont.) TED Example

The code for the TED application is available on the student network.

Control Form TextBox CheckBox CheckBox CheckBox CommandButton CommandButton CommandButton CommandButton

Name frmTed txtTed chkBold chkItalic chkUnderline cmdDelete cmdCut cmdCopy cmdPaste

Note the naming conventions used for all the VB objects (controls). Refer Appendix - VB Naming Conventions - for more information.

b0688454-8000-4686-aa20-1e43dba5c849.doc

15

Information Technology Studies

Programming in Visual Basic for Windows

4. VB Controls (cont.) Control Arrays Definition : A set (two or more) of controls that have the same name.

Sometimes we may want many controls to respond to the same event, eg. click or change event, in the same way. Rather than writing the same code many times for each object we can get VB to call the one event handling procedure by using control arrays.
 

A set of controls that share the same name property but have unique values for the Index property. Events generated by these controls share common event procedures, but are uniquely identified by the Index argument passed to the event routine.

Advantages of Control Arrays :
  

Code can manipulate a group of controls more efficiently Several controls can share the same event procedure Add or delete elements of a Control Array at run time Control Name chkStyle chkStyle chkStyle Index Value Index = 0 Index = 1 Index = 2

Control chkBold chkItalic chkUnderline

Access Keys Definition : A keyboard shortcut key to quickly access a control. An access key gives the user quick keyboard access to a menu, command, or control. Unlike shortcut keys, access keys don't necessarily execute commands when pressed. At design time, you designate a letter in the caption of the control to be the access key. At run time, this letter is underlined, and the user can access the menu or command by pressing ALT plus the letter Nominate the access key as a character in the caption by preceding the character with the ampersand symbol (&). eg. a form exit command button cmdExit.Caption = "e&Xit" (this will appear as eXit and can be activated by Alt+X)

b0688454-8000-4686-aa20-1e43dba5c849.doc

16

Information Technology Studies

Programming in Visual Basic for Windows

5. DATA TYPES AND DATA HOLDERS


VB has 11 fundamental Data Types :
Data Types

Numbers

Text

Combination

Floating Point

Whole Numbers

Monetary

Single Precision


Double Precision

Integer

Long Integer

Currency

Variable-length String

Fixed-length String

Variant

Range Of Values Data Type Byte Boolean Integer Long Single (7 digits) Double (15 digits) Currency (15.4 dig.) Date String - fixed String - variable Variant Object User-Defined Range 0 to 255 True or False ± 32,768 ± 2,147,483,648 ± 3.4E+38 ± 1.8D+308 ± 922,337,203,685,477.5808 1/1/100 to 31/12/9999 0 to 65,500 0 - 65,500 (16-bit) or 2 billion (32-bit) Any of the above data types Reference (pointer) to an object Combination of fundamental types

Data References
 

variable names literal

eg. MyAge, LastName, TotalScore, Count eg. 21, “Smith”, 98.45, "This is a string"

Data Holders


Variable



Constant



Array



Record (user-defined data type)

b0688454-8000-4686-aa20-1e43dba5c849.doc

17

Information Technology Studies

Programming in Visual Basic for Windows

5. Data Types and Data Holders (cont.) Using Variables Naming Variables
    

first character must be alphabetic other characters can be alphanumeric or underscore <= 255 characters in length cannot be a reserved word not case-sensitive eg. the following names all refer to the same variable: MyAge, MYAGE, myage, myAGE

Assigning Data Types to Variables Any of the following methods are possible but Method 1 is recommended 1. 2. As clause eg. Dim IndexNo As Integer Dim Surname As String

Type-declaration suffix character - NOT recommended Final character can be a data type declaration character. It is recommended that this method NOT be used but that all variables be explicitly declared as per Method 1. Character % & ! # @ $ Data Type Integer Long Single Double Currency String Variant eg. No of Bytes 2 4 4 8 8 n 16+

Dim IndexNo% Dim Surname$

3.

Deftype where type can be Bool, Byte, Int, Lng, Cur, Sng, Dbl, Date, Str, Obj, Var Declares that variables beginning with particular letters have a specified data type. eg. DefInt A-C DefStr S-R, X-Z DefDate D

This method is also NOT recommended. 4. Nothing (default is Variant data type). This is definitely NOT recommended.

b0688454-8000-4686-aa20-1e43dba5c849.doc

18

Information Technology Studies

Programming in Visual Basic for Windows

5. Data Types and Data Holders (cont.) Declaring and Assigning Variables The keywords Option Explicit force all variables to be declared before they can be used (refer menu: Tools…Options...Editor…Require variable declaration). Important : Please ensure this option is selected.


Variable Declaration Examples Dim varname As type eg. Dim TotalScore As Integer Dim LastName As String * 20 Dim Salary As Currency



Variable Assignments varname = expression object.property = expression NOTE: the equals sign (=) means is now assigned the value of (when assigning values to variables it does not mean „is equal to‟) eg. MyTemp = 98.6 LastName = "Smith" cmdExit.Caption = "Exit" txtSalary.Text = Salary Score = CInt(txtScore.Text) TotalScore = TotalScore + Score NumItems = 20 * NumBoxes MyAge = BigNum

b0688454-8000-4686-aa20-1e43dba5c849.doc

19

Information Technology Studies

Programming in Visual Basic for Windows

5. Data Types and Data Holders (cont.) Using Constants [Public] Const CONSTNAME = expression eg. Const TITLE As String = "Visual Basic" Const TOP_SCORE AS Integer = 100 Const START_DATE As Date = #8/12/1990# Const END_DATE As Date = #18/6/1992# Const MIN_WAGE As Currency = 555.55 Const TAX_RATE_2 As Single = .32 Const MAX_WEIGHT As Single = 538.5 Const MIN_WEIGHT As Single = MAX_WEIGHT – 200 Constants are usually placed in a standard code module (often called GLOBAL.BAS). By convention user-defined constants are usually declared (typed) in UPPERCASE. eg. Public Const TICKET_COST As Currency = 99.95 Num_Tickets = Val(InputBox(“Enter number of tickets”)) Customer_Cost = Num_Tickets * TICKET_COST VB has intrinsic constants for most possible values of actions and properties. See the online help or the Object Browser for them (refer menu: View…Object Browser):

b0688454-8000-4686-aa20-1e43dba5c849.doc

20

Information Technology Studies

Programming in Visual Basic for Windows

5. Data Types and Data Holders (cont.) Introduction to Arrays Definition :   An array is a meaningful name given to a range of memory locations (addresses) to store groups of related data of the same data type.

Array variables can contain data of type: Byte, Boolean, Integer, Long Integer, Single, Double, Currency, Date, String, Variant, User-Defined and Objects (Controls, Forms etc). Array variables consist of a name and index number (subscript). eg. Dim Students(1 To 20) Students(1) = 80 Students(2) = 85 Students(3) = 100 ... ... Students(20) = 60 As Integer

Introduction to Records Definition :     A record is a user-defined data type made up of multiple elements, where the elements may hold different types of data.

Also referred to as a user-defined data type, combination data type, or structure. Allows custom design of a unique data type for a particular application. Like an array, a record is a structured data type made up of multiple elements. Unlike an array, elements of a record can be different data types. eg. Type FamilyRecord LastName As String * 20 FirstName AS String * 20 DateOfBirth As Date End Type Dim MyFamily As FamilyRecord MyFamily.LastName = “Adams” MyFamily.FistName = “Uncle Fester” MyFamily.DateOfBirth = #1/1/1900#

Note: Arrays and Records will be covered in greater detail later in the course.

b0688454-8000-4686-aa20-1e43dba5c849.doc

21

Information Technology Studies

Programming in Visual Basic for Windows

Program Comments Maxim: every minute spent writing comments will save at least 10 minutes later on, or, the sooner you start coding the longer your project will take!! eg. Private Sub CalculateTax() „calculates and outputs the tax payable „called by cmdCalculate_Click event „written by Joe Programmer 29/11/98 „modified 8/12/98 to include data conversion functions Salary = CCur(Val(txtSalary.Text)) TaxRate = CCur(Val(txtTaxRate.Text)) Tax = Salary * TaxRate lblTax.Caption = CStr(Tax) End Sub „input salary „input tax rate „calculate tax „output tax

NOTE: avoid following trap: Client = "ABC Plumbing" „Get rate: Rate = 3.1

Recommendations : Always ensure the keywords OPTION EXPLICIT are in the general declarations section of EVERY module within your project as this will force (ensure) the declaration of all variables. Use comments liberally throughout your code - remember that they are an important part of a projects internal documentation process.

b0688454-8000-4686-aa20-1e43dba5c849.doc

22

Information Technology Studies

Programming in Visual Basic for Windows

Student Notes (Topics 3, 4 and 5)

b0688454-8000-4686-aa20-1e43dba5c849.doc

23

Information Technology Studies

Programming in Visual Basic for Windows

6. OPERATORS Arithmetic Operators Symbol + * / ^ \ Mod String Operators Symbol & or + Name Concatenation Name Addition Subtraction Multiplication Division Exponentiation Negation Integer Division Remainder

Note: use the ampersand symbol (&) rather than (+) for string concatenation eg. Dim FirstName As String Dim LastName As String Dim FullName As String FirstName = "Coca" LastName = "Cola" FullName = FirstName & LastName

Relational Operators Also referred to as the „Comparison Operators‟ – used for comparing one value to another Symbol = <> > < >= <= eg. If OurScore > TheirScore Then MsgBox "We Won" End If Name Equals Not equal Greater than Less than Greater than or equal to Less than or equal to

b0688454-8000-4686-aa20-1e43dba5c849.doc

24

Information Technology Studies

Programming in Visual Basic for Windows

6. Operators (cont.) Logical Operators Symbol Not And Or Xor Eqv Imp Name Logical negation Conjunction Inclusive or Exclusive or Equivalence Implication

(Note: You will not need to use Xor, Eqv or Imp in this subject) eg. If Not Age > 30 Then ... If (Age > 30) And (Weight > 100) Then ... If (Fname = "Jim") Or (Sname = "Smith") Then ...

Operator Precedence Symbol ^ *, / \ Mod +, =, >, <, <>, >=, <= Not And Or Xor Eqv Imp Name Exponentiation Negation Multiplication and Division Integer Division Remainder Addition and Subtraction Relational operators Logical negation Conjunction Inclusive or Exclusive or Equivalence Implication Type Arithmetic Arithmetic Arithmetic Arithmetic Arithmetic Arithmetic Relational Logical Logical Logical Logical Logical Logical

Expression are evaluated from left to right only when operators are of equal value Parenthesis (brackets) are used to override standard operator precedence eg. 4 + 3 * 2 (4 + 3)* 2 „value is 10 „value is 14

The liberal use of brackets, for clarity, is strongly recommended in your code.

b0688454-8000-4686-aa20-1e43dba5c849.doc

25

Information Technology Studies

Programming in Visual Basic for Windows

7. VISUAL BASIC PROJECTS Forms  A form object is used to create the applications main window and any dialogue boxes that the application may need.  A dialogue box is a form that collects the users information and choices, they do not generally include menus, window scroll bars, resizing buttons, status bars or control bars, as other windows would.  Forms have properties that determine aspects of their appearance such as position, size and colour; and aspects of their behaviour such as whether or not they are resizable.  Forms can also respond to events initiated by a user or triggered by the system. For example, you could write code in a form's click event procedure that would enable the user to change the colour of a form by clicking on it.  In addition to properties and events, you can use methods to manipulate forms using code. For example, the show method (Form1.Show) will immediately display a form on the screen.  You can create multiple instances of forms in code by using the New keyword combined with Dim, Set and Static statements.  Forms can be loaded into memory and be either visible (on the screen) or invisible. This is achieved during run time by using code to invoke the Hide and Show methods of the form. You can also move forms in and out of memory using the Load and Unload commands  When designing forms, set the BorderStyle property to define a form's border, and set the Caption property to put text in the title bar (note: setting BorderStyle to 0 removes the border). If you want a form to have a border without the TitleBar, Control-menu box, Maximize and Minimize buttons then delete any text from the form's Caption property, and set the form's ControlBox, MaxButton, and MinButton properties to False.  You can access the collection of forms within a project using the Forms Collection.  You can access the collection of controls on a form using the Controls Collection. For example, to hide all the controls on a particular form you could use code similar to the following: Dim MyControl as Control For Each MyControl in Form1.Controls MyControl.Visible = False Next MyControl

b0688454-8000-4686-aa20-1e43dba5c849.doc

26

Information Technology Studies

Programming in Visual Basic for Windows

7. VB Projects - Forms (cont.) Form Properties ActiveControl ActiveForm Appearance AutoRedraw BackColor BorderStyle Caption ClipControls ControlBox Count CurrentX CurrentY DrawMode DrawStyle DrawWidth Enabled FillColor FillStyle Font FontBold Form Events Activate Click Dblclick DragDrop DragOver Gotfocus KeyUp KeyDown Form Methods Circle Cls Hide Item Line Move PaintPicture Point

FontItalic FontName FontSize FontStrikethru FontTransparent FontUnderline ForeColor hDC Height HelpContextID hWnd Icon Image KeyPreview Left LinkMode LinkTopic MaxButton MDIChild MinButton

MouseIcon MousePointer Name NegotiateMenus NewEnum Picture ScaleHeight ScaleLeft ScaleMode ScaleTop ScaleWidth ShowInTaskbar Tag Top Visible WhatsThisButton WhatsThisHelp Width WindowState

KeyPress LinkClose LinkOpen LinkError LinkExecute Load LostFocus MouseDown

MouseUp MouseMove Paint QueryUnload Resize Unload

PopupMenu Print PrintForm PSet Refresh Scale ScaleX ScaleY

SetFocus Show TextHeight TextWidth WhatsThisMode ZOrder

Note: for this subject we’ll be using properties, events and methods shown in bold, we may touch on those appearing in italics, you do not need to know the others.
b0688454-8000-4686-aa20-1e43dba5c849.doc

27

Information Technology Studies

Programming in Visual Basic for Windows

7. VB Projects - Forms (cont.) Multiple Forms Existing forms and modules for a project may be added and removed via the Project menu. New forms and modules are created using the Project…Add… menu. Custom controls (OCX) are added and removed using the Project…Components… menu. (eg. the Microsoft Common Dialog Control)


First Form The start up form, specified in menu Project…Properties…General…Startup Object…, names the first form that appears. NOTE: If there is no start up form, we can use Sub Main (a user defined general procedure)



Other Forms Accessed at run-time by following commands: Load formname
 

places formname in memory Form_Load event is triggered

formname.Show modestyle
 

displays formname onto screen modestyle = vbmodal for a modal form
(refer VB Help for more information on Form Constants)

NOTE : A form will automatically load if you only use show and it is not already loaded. formname.Hide


makes formname invisible

Unload formname


removes formname from memory

eg. see CONTROLS.VBP in the VB\SAMPLES\CONTROLS directory

b0688454-8000-4686-aa20-1e43dba5c849.doc

28

Information Technology Studies

Programming in Visual Basic for Windows

7. Visual Basic Projects (cont.) Text Boxes  A TextBox control is primarily used for data input from the user. In other visual interfaces it may be called an Edit Field or simply Field.  To display multiple lines of text in a TextBox, set the MultiLine property to True. If a multipleline TextBox doesn't have a horizontal scroll bar, text wraps automatically even when the TextBox is resized. To customise the scroll bar combination on a TextBox, set the ScrollBars property. Properties Alignment Appearance BackColor BorderStyle Container DataChanged DataField DataSource DragIcon DragMode Enabled Font FontBold FontItalic FontName FontSize

FontStrikethru FontUnderline ForeColor Height HelpContextID HideSelection hWnd Index LinkItem LinkMode LinkTimeout LinkTopic Locked MaxLength MouseIcon MousePointer

MultiLine Name Parent PasswordChar ScrollBars SelLength SelStart SelText TabIndex TabStop Tag Text Top Visible WhatsThisHelpID Width

Events Change Click DblClick DragDrop DragOver GotFocus

KeyDown KeyPress KeyUp LinkClose LinkError LinkNotify

LinkOpen LostFocus MouseDown MouseMove MouseUp

Methods Drag LinkExecute LinkPoke

LinkRequest Move Refresh

SetFocus ShowWhatsThis ZOrder

Note: for this subject we‘ll be using properties, events and methods shown in bold, we may touch on those appearing in italics, you do not need to know the others.

b0688454-8000-4686-aa20-1e43dba5c849.doc

29

Information Technology Studies

Programming in Visual Basic for Windows

7. Visual Basic Projects (cont.) Common Dialog Control   Provides a standard set of dialog boxes, as common to most windows applications. Displayed by using one of the following methods:

Method ShowOpen ShowSave ShowColor ShowFont ShowPrinter ShowHelp

Type of Dialog Box Displayed File Open Save As Colour Font Print Invokes Windows Help file



The following instruction displays a Save As dialog box: dlgMyDialog.ShowSave Can be customised by modifying the value of the Flag property eg. The following instruction allows multiple filenames to be selected in the File Open dialog box: dlgMyDialog.Flags = cdlOFNAllowmultiSelect The VB Object Browser shows the symbolic constants for each permissible value of Flags. Use these constants instead of numbers.



The following instruction displays a Color dialog box: dlgMyDialog.ShowColor eg. Sub mnuOptionsBackColour_Click „change the back colour of the form dlgMyDialog.ShowColor frmTed.BackColor = dlgMyDialog.Color End Sub

b0688454-8000-4686-aa20-1e43dba5c849.doc

30

Information Technology Studies

Programming in Visual Basic for Windows

7. Visual Basic Projects (cont.) The .VBP File    VB projects usually consist of a number of files, which are managed by the project.vbp file. Usually referred to as the project file and may be viewed (even edited) with a text editor. Component files of a Visual Basic Project: File Type Form Code Module Class Module Binary Data Custom Control (Object) Reference to system DLL Binary resource file Log for loading errors Project workspace file  Extension .FRM .BAS .CLS .FRX .VBX, .OCX .DLL .RES .LOG .VBW

Applications may access DLL's and other applications (via OLE, DAO, ActiveX etc.) at run time. Note - VB projects prior to VB Version 4 have the file extension MAK (not VBP)

Making an EXE file    Select menu: File…Make EXE…to make a project into an executable file. Select menu: Project…Properties…Make to set version control information for a project. VB executable applications can be executed from an icon or from the Command Line. A Command Line Parameter to modify an application‟s behaviour can be set by selecting the menu: Project…Properties…Make Tab.

b0688454-8000-4686-aa20-1e43dba5c849.doc

31

Information Technology Studies

Programming in Visual Basic for Windows

Student Notes (Topics 6 and 7)

b0688454-8000-4686-aa20-1e43dba5c849.doc

32

Information Technology Studies

Programming in Visual Basic for Windows

8. SEQUENCE STATEMENTS VB Instructions
   

length of line <= 1024 characters line continuation character is _ (underscore) multiple instructions per line, separated by a colon : (not recommended) labels can be numeric (a carry over from BASIC line numbers – not recommended) alphanumeric (ending with a : (colon) eg. ErrorHandler: ) comments appear anywhere on a line - using apostrophe ' (or using Rem keyword – not recommended) eg. Sub cmdCalculate_Click () Rem Routine to calculate the loan payment 'the apostrophe (single quote character) 'is a better alternative to the Rem keyword



 

Instructions are executed "top-down" line-by-line from the top of the procedure to the bottom. Instruction sequence can be altered by: Unconditional Branch GoTo label [linenumber] Conditional Branch On numexpr GoTo labellist [linenolist] eg. (not recommended)

-

(not recommended, except for error handling)

Dim Choice as Integer . . . On Choice GoTo Solo, Duet, Trio, Quartet MnuChoice = 1 2 3 4 branch to label: “ “ “ Solo Duet Trio Quartet

These branching statements should be avoided where possible (i.e. follow structured programming principles – procedures to have only One Entry Point and One Exit Point) Program Termination End 33

b0688454-8000-4686-aa20-1e43dba5c849.doc

Information Technology Studies

Programming in Visual Basic for Windows

9. SELECTION STRUCTURES The If Statement


single line If Format 1: If condition Then statement statement is executed if condition is True eg.1 If Age < 20 Then MsgBox "Young" eg.2 If Surname = "Smith" Then Pay = 30000 Format 2: If condition Then statement1 Else statement2 statement1 is executed if condition is True statement2 is executed if condition is False eg.1 If Age < 20 Then MsgBox "Young" Else MsgBox "Old" NOTE: statement may contain multiple instructions (not recommended) eg.2
If Score > 500 Then Rate = 3.5: Num = 29 Else Rate = 2.6: Num = 42



multiple line If Format 3: If condition Then statement(s)1 Else statement(s)2 End If statement(s)1 is executed if condition is True statement(s)2 is executed if condition is False

b0688454-8000-4686-aa20-1e43dba5c849.doc

34

Information Technology Studies

Programming in Visual Basic for Windows

9. Selection Structures (cont.) Format 3: (cont.) eg.1 If Score > 500 Then Rate = 3.5 Num = 29 Else Rate = 2.6 Num = 42 End If eg.2 (nested if) Dim Age as integer Age = Val(InputBox(“Enter Age”)) If Age < 13 Then MsgBox “Child” Else If Age < 20 Then MsgBox “Teenager” Else MsgBox “Adult” End If End If

THE ABOVE IS THE RECOMMENDED FORMAT (Format 3)

Format 4: If condition1 Then statement(s)1 ElseIf condition2 Then statement(s)2 ElseIf condition3 Then statement(s)3 Else statement(s)4 End If

b0688454-8000-4686-aa20-1e43dba5c849.doc

35

Information Technology Studies

Programming in Visual Basic for Windows

9. Selection Structures (cont.) Format 4: (cont.) eg.1 If MyNumber = 0 Then MsgBox "Zero" ElseIf MyNumber = 1 Then Total = Total + 1 MsgBox "One" ElseIf MyNumber >= 2 Then Total = Total + 2 MsgBox "Greater than one" Else MsgBox "Negative" End If

eg.2 If Score < 50 Then Result = "Fail" ElseIf Score < 70 Then Result = "Pass" ElseIf Score < 90 Then Result = "Credit" Else Result = "Distinction" End If

Note : This is a reasonable format but, when solving problems involving multiple choice selection, consider using the case structure as a better alternative in many situations.

b0688454-8000-4686-aa20-1e43dba5c849.doc

36

Information Technology Studies

Programming in Visual Basic for Windows

9. Selection Structures (cont.) Boolean Expressions
 

A Boolean expression is a test expression that evaluates to True or False. Internally VB represents Boolean values as integers: 0 -1 False True

 

When using integers any non-zero number converts to a Boolean value of True. Can include arithmetic, relational and logical operators eg. If ((Score = 300) And (Game = “Bowling”)) Then Result = "Perfect" End If Instead of using integers, use the BOOLEAN data type to store boolean values. Boolean data types occupy 2 bytes of memory, same as the integer data type. eg. Dim Found as Boolean, ValidData as Boolean etc.





Table of Results of Logical Operators: Operand Value A B T T T F F T F F Value of Logical Operation A And B A Or B A Xor B A Eqv B T T F T F T T F F T T F F F F T

Not A F F T T

A Imp B T F T T



A Complex Boolean Expression is an expression that contains more than one boolean expression. eg.
If ((Chr <> “Y”) And (Chr <> “y”) And (Chr <> “N”) And (Chr <> “n”) Then MsBBox “Data Entry Error – Please enter Y or N”



Testing With Control Variables If TypeOf cvname Is cvtype Then statement(s) End If eg. If TypeOf MyControl Is TextBox Then Result = "OK" End If

b0688454-8000-4686-aa20-1e43dba5c849.doc

37

Information Technology Studies

Programming in Visual Basic for Windows

9. Selection Structures (cont.) The Case Statement Syntax: Select Case expression Case testlist statement(s) Case testlist statement(s) . . . . . . Case Else statement(s) End Select


testlist is one or more test expressions, separated by commas: Type Relational Equality Equality (implied "=") Explicit range Multiple eg. Dim Age as Integer Age = Val(InputBox(“Enter Age”) Select Case Age Case 0 To 12 MsgBox "Child" Case 13 To 19 MsgBox "Teenager" Case Is > 19 MsgBox "Adult" Case Else MsgBox "Impossible" End Select 'range 'range 'relational 'case else Example Case Is >= 39 Case Is = 21.6 Case 21.6 Case -7 To 7 Case Is <> 14, Is < 101



or consider validating the data before passing control to a select case structure: eg. If (Age < 0) Or (Age > 130) Then MsgBox (“Invalid age entered”) End If

b0688454-8000-4686-aa20-1e43dba5c849.doc

38

Information Technology Studies

Programming in Visual Basic for Windows

10. ITERATION STRUCTURES (LOOPING)

VB provides 4 iteration structures:
   

For Next Loop Do While Loop (top and bottom test formats) Do Until Loop (top and bottom test formats) For Each Next Loop (arrays or collections only)

Choosing an Iteration Structure:
Choosing a Loop Structure

Is the number of repetitions known in advance ?

yes For - Next

Must the loop execute at least once ?

no Do - Loop (top test)

yes

Do - Loop (bottom test)

Note: VB still includes a While-Wend Loop, mainly for backwards compatibility purposes. The newer Do-Loop comes in many forms and should, nowadays, always be used instead of a WhileWend. If the loop is to execute at least once use a bottom test format Do-Loop and if the loop does not need to execute at least once use a top test format Do-Loop (see section on Do Loop Structure).

b0688454-8000-4686-aa20-1e43dba5c849.doc

39

Information Technology Studies

Programming in Visual Basic for Windows

10. Iteration Structures (cont.) For - Next Structure Format 1: - single-line (not recommended) For cv=start To end [Step incr]: … : Next [cv]

Format 2: - multiple line (recommended) For countervar = start To end [Step incr] . . . . . . 'body of loop . . . Next [countervar] Format 2 is recommended - note indenting of all instructions inside loop
 

uses a counter variable which is incremented automatically start, end and incr can be: - literal (eg. 1 To 10) byte; single; double; integer (preferred); double; currency

- variable of data type:

(eg. CurrentRecord To LastRecord) eg.1 Dim Number as Integer Dim Square as Integer For Number = 0 To 6 Square = Number * Number Print Number, Square Next Number eg.2 Dim Index as Integer For Index = 0 To 10 Step 2 Print Index Next Index

b0688454-8000-4686-aa20-1e43dba5c849.doc

40

Information Technology Studies

Programming in Visual Basic for Windows

For - Next Structure (cont.)


Nesting For loops For loops can be nested to any level Innermost loops execute the fastest Each loop must use a unique counter variable Use indentation for clarity

eg.1 Const MAX As Integer = 5 Dim Product As Integer Dim A As Integer, B As Integer For A = 1 To MAX For B = A To MAX Product = A * B Print A, B, Product Next B Print Next A eg.2 Dim Outer As Integer Dim Inner As Integer For Outer = 1 To 3 For Inner = 1 To 5 Print Outer, Inner, Outer + Inner Next Inner Print Next Outer eg.3 For Outer = 1 To 3 For Inner = 1 To 2 Print “Hip!” Next Inner Print “HOORAY!!” Next Outer


Exit For statement is used to terminate loop prematurely. This leads to poorly structured code and should be avoided.

b0688454-8000-4686-aa20-1e43dba5c849.doc

41

Information Technology Studies

Programming in Visual Basic for Windows

10. Iteration Structures (cont.) Do - Loop Structure Pre-Test Format:
     

uses a Boolean expression which evaluates to True or False boolexpr tested at start of loop before executing body with While body is executed as long as boolexpr is True with Until body is executed as long as boolexpr is False (ie. until True) Do Loops can be nested to any level also known as the top test loop Do While boolexpr . . . Loop or Do Until boolexpr . . . Loop

'body of loop

'body of loop

eg. Sub Countdown() „Demonstrate Do While Loop – Top Test Format Dim TimeLeft As Integer TimeLeft = 10 Do While TimeLeft > 0 „boolean condition Print TimeLeft TimeLeft = TimeLeft - 1 Loop Print „blank line Print “BLAST OFF!” End Sub Output of CountDown is: 10 9 . . 2 1 BLAST OFF!

b0688454-8000-4686-aa20-1e43dba5c849.doc

42

Information Technology Studies

Programming in Visual Basic for Windows

Do - Loop Structure (cont.) Post-Test Format:
    

boolexpr tested at end of loop after body is executed with While body is executed as long as boolexpr is True with Until body is executed as long as boolexpr is False (ie. until True) Do Loops can be nested to any level also known as the bottom test loop Do ... „body of loop Loop While boolexpr or Do ... 'body of loop Loop Until boolexpr eg. „Demonstrate Do Until Loop – Bottom Test Format Dim Number As Integer Do Number = Val(InputBox$(“Type a number”)) If (Number > 0) Then MsgBox “You‟re Positive” Else If (Number < 0) Then MsgBox “You‟re Negative” End If End If Loop Until (Number = 0) Note the following are equivalent: 1. Do ... Loop Until Num = 0 Do ... Loop While Num <> 0

2.

Do Until X > 5 ... Loop

Do While X <= 5 ... Loop



Exit Do statement used to terminate loop prematurely but should not ever need to use it (remember structured programming - one entry point, one exit point).

b0688454-8000-4686-aa20-1e43dba5c849.doc

43

Information Technology Studies

Programming in Visual Basic for Windows

10. Iteration Structures (cont.) For Each - Next Structure VB has a For Each - Next Structure for iterating through collections, namely the Forms and Controls Collections. Can also be used to iterate through variable and control arrays. For Each element in group ... 'body of loop Next [element]
  

element is a variant or object variable group is an array or a collection example 1: iterating through an array (could also use a standard For - Next Loop) ReDim MyArray(1 To 5) As Date Dim Element As Variant MyArray(2) = #21/08/1996# For Each Element In MyArray MsgBox Format$(Element, "Short Date") Next Element



example 2: iterating through all controls on the form. Every form has a property „controls‟. It contains all controls on that form (ie. the Controls Collection). eg.1 Dim MyControl As Control For Each MyControl In Me.Controls MsgBox MyControl.Name Next MyControl

eg.2 Dim X As Control For Each X In frmTed.Controls If TypeOf X Is CommandButton Then X.Enabled = False End If Next X

Note: for this subject we will be using standard For - Next Loops, and Do Loops. You will not need to remember the above For Each - Next structure.

b0688454-8000-4686-aa20-1e43dba5c849.doc

44

Information Technology Studies

Programming in Visual Basic for Windows

10. Iteration Structures (cont.) A programming example that uses Control Arrays, Looping and Selection structures. Program Specification A prototype program is required to determine if a multiple choice questionnaire has been correctly filled in. The program is to allow for 3 questions with responses of A, B, C, D or E. If more than one box is checked output a message „invalid‟, if no boxes are checked output „check a box’, otherwise output „OK‟. Use a control array of labels for the message and 3 control arrays for the check boxes.

Program Code
Option Explicit ‘solution written by Don Galvin 'Question 1 has 5 check boxes in a Control Array called chkAnswer1 'Question 2 has 5 check boxes in a Control Array called chkAnswer2 'Question 3 has 5 check boxes in a Control Array called chkAnswer3 'Each Question has a result label in a Control Array called lblCheck 'therefore the code below will execute when any label is clicked. Private Sub lblCheck_Click(Index As Integer) '3 labels in a Control Array Dim Counter As Integer 'variable to control the For...Next Loops Dim NumChecked As Integer 'count number of boxes checked Select Case Index 'each label has a unique index Case 0 'first label (Index 0) For Counter = 0 To 4 'loop through Q.1's five check boxes If chkAnswer1(Counter).Value = 1 Then 'if checked then NumChecked = NumChecked + 1 'increment (add 1) End If Next Counter 'end of For...Next Loop Case 1 'second label (Index 1) For Counter = 0 To 4 'loop through Q.2's five check boxes If chkAnswer2(Counter).Value = 1 Then 'if checked then NumChecked = NumChecked + 1 'increment (add 1) End If Next Counter 'end of For...Next Loop Case 2 'third label (Index 2) For Counter = 0 To 4 'loop through Q.3's five check boxes If chkAnswer3(Counter).Value = 1 Then 'if checked then NumChecked = NumChecked + 1 'increment (add 1) End If Next Counter 'end of For...Next Loop End Select 'end of 1st select case structure Select Case NumChecked 'select on number of boxes checked Case 0 'if no boxes checked lblCheck(Index).Caption = "Check a box" Case 1 'if one box checked lblCheck(Index).Caption = "O.K." Case Is >= 2 'if 2 or more boxes checked lblCheck(Index).Caption = "Invalid" End Select 'end of 2nd select case structure End Sub

b0688454-8000-4686-aa20-1e43dba5c849.doc

45

Information Technology Studies

Programming in Visual Basic for Windows

Student Notes (Topics 8, 9 and 10)

b0688454-8000-4686-aa20-1e43dba5c849.doc

46

Information Technology Studies

Programming in Visual Basic for Windows

11. VARIABLE AND PROCEDURE SCOPE
 

A variable is a meaningful name given to a computer memory location (address). Scope refers to the visibility of an identifier within a project, whether it be an object, variable, constant, sub procedure or function. All declarations have a default scope and visibility: Type of declaration Dim Const Public Sub Procedure Function Property Place of declaration Procedure Form Module procedure (private) form (private to form) procedure (private) form (private to form) not allowed not recommended** not allowed private not allowed private not allowed public



Code Module module (private) module (private) public public public public

** Variables may be declared as Public inside a Form Module but it is not recommended.


The default visibility can be overridden using the keywords: Private or Public.
Project .VBP file public variables (global to whole project) - declared in code modules (bas files)

Form Modules module (form) level variables General & Event Procedures local & static variables

Code Modules module level & public variables General Procedures local & static variables

b0688454-8000-4686-aa20-1e43dba5c849.doc

47

Information Technology Studies

Programming in Visual Basic for Windows

11. Variable and Procedure Scope (cont.) Variable Lifetime:
 

The duration of the identifier (variable) in memory. There are two types of memory allocation: Allocation Type Dynamic Static Lifetime Temporary Permanent

Local Variables Local (private) variables declared within a procedure are dynamic and their value is only retained in memory whilst that procedure is running, ie. memory allocation is temporary. Static Variables Variables declared with the Static keyword retain their value as long as the program is running, ie. the variable value remains preserved between successive calls to the procedure in which the variable is defined. Public Variables Variables declared with the Public keyword retain their value as long as the program is running, ie. they are global variables and their value is preserved the whole time the program is in memory. Public variables can be seen and accessed from anywhere within the application, and they must to be declared at the module level, they cannot be declared within a procedure. Variables declared with Dim in the General Declarations section of a module are global (public) to the module in which they are declared. eg. Option Explicit Public gTotalClicks as Integer Dim mFormClicks as Integer Private Sub CountTheMouseClicks() Static ClickCount As Integer Dim Index as Integer ... ClickCount = ClickCount + 1 ... End Sub Scope - Lifetime Relationships:
   

„Public Variable „Module Variable „Static Variable „Local Variable

Most Public variables are static (those declared within a code module are static). Form Module level variables are static (ie. as long as the form remains in memory). Code Module level variables are static (because a code module remains in memory). Local (procedure level) variables can be declared (dimensioned) as dynamic or static.

Recommendation : Declare all variables as locally as possible, ie. try to minimise the use of Form Level and Public (global) variables.

b0688454-8000-4686-aa20-1e43dba5c849.doc

48

Information Technology Studies

Programming in Visual Basic for Windows

12. DEBUGGING


VB's interactive environment provides three modes of operation: 1. 2. 3. Design mode Run mode Break mode



VB's debugging features become available whenever an application is in Break mode.

Break Mode


You enter Break mode while an application is running by: pressing Ctrl + Break choose Break from the Run menu click the Break icon on the Toolbar encountering a run-time error program execution reaches a preset breakpoint a watchpoint expression changes or reaches a preset value VB encounters a Stop instruction



When in Break mode, VB retains current values of variables, expressions and property values.

b0688454-8000-4686-aa20-1e43dba5c849.doc

49

Information Technology Studies

Programming in Visual Basic for Windows

12. Debugging (cont.) Debugging Features


Debug (immediate) Window where you can : 1. display (Print or ?) values of variables, expressions or property values; 2. change values of variables or properties; 3. call (execute) individual procedures. Locals and Watches Windows where you can track the values of variables, expressions etc. Instant Watch: whilst in Break Mode simply point to a variable to see its value. Program Tracing: a line-by-line examination of your program's logic flow including single step (F8) and procedure step (Shift + F8) - important that you remember this. Breakpoint: a specified program line on which you want to suspend execution. Watchpoint: a specified condition at which you want to suspend execution. Calls dialog box: shows which modules and procedures are involved in the chain of execution at the time it is suspended. Set Next: allows you to designate which instruction will execute next. Stop statement: allows you to set a breakpoint directly in the program code. Debug Toolbar: containing the most commonly used debugging tools. Auto Editor Options: see menu Tools…Options…Editor Tab which include: syntax check, variable declaration, list members, quick info, and data tips.

  

  

   

b0688454-8000-4686-aa20-1e43dba5c849.doc

50

Information Technology Studies

Programming in Visual Basic for Windows

Student Notes (Topics 11 and 12)

b0688454-8000-4686-aa20-1e43dba5c849.doc

51

Information Technology Studies

Programming in Visual Basic for Windows

13. PROCEDURES Divide and Conquer It is much easier to complete a collection of smaller tasks than to tackle one large one.
    

General procedures provide a technique for defining your own statements, methods, and functions to supplement those built into VB. Can be defined at the form or module level. Isolated from other program components. Use local variables. Can pass parameter values back and forth to the calling instruction (parameters can be variables, expressions, controls or even forms). This is a very important concept that you will need to understand. VB supports three types of procedures: 1. 2. 3. Sub Procedures (can be either Event Procedures or General Procedures). User-Defined Functions (to supplement the in-built functions that ship with VB). Property Procedures (add custom properties to forms and modules; execute code when property is set or retrieved). Property Procedures will not be covered in this subject.



Creating a new procedure.


A new procedure can be created either by typing it directly in the code window or by using the Tools…Add Procedure... menu option:

b0688454-8000-4686-aa20-1e43dba5c849.doc

52

Information Technology Studies

Programming in Visual Basic for Windows

13. Procedures (cont.) Sub Procedures Definition: a sub procedure should perform a single specific task. [Private] Sub subname [(paramlist)] [Instructions] End Sub

„general procedure

Sub Cross(X As Integer, Y As Integer, LengthX As _ Integer, LengthY As Integer) Line(X, Y) - Step(LengthX, 0) Line(X, Y) - Step(-LengthX, 0) Line(X, Y) - Step(0, LengthY) Line(X, Y) - Step(0, -LengthY) End Sub Sub cmdDrawCross_Click() „event procedure Call Cross(4000, 2000, 3000, 1500) End Sub or Sub cmdDrawCross_Click() „event procedure Dim Xcenter as Integer Dim Ycenter as Integer Xcenter = 4000 Ycenter = 2000 Call Cross(Xcenter, Ycenter, 3000, 1500) End Sub User-Defined Functions Definition: a function performs an action and returns a value. [Private] Function funcname [(paramlist)] As type [Instructions] funcname = expression End Function Similar to a Sub procedure, except functions return a single value. e.g. Function Square(NumValue As Double) As Double Square = NumValue * NumValue End Function lblResult.Caption = Square(4) or or Print Square(LengthValue) Area = Square(2.3 + 3.1) - Square(LengthValue)

b0688454-8000-4686-aa20-1e43dba5c849.doc

53

Information Technology Studies

Programming in Visual Basic for Windows

13. Procedures (cont.) Passing Parameters


Parameter declaration syntax: [Optional][ByVal|ByRef][ParamArray] varname[( )][As type]



Number of arguments in argumentlist and paramlist must be the same, unless parameters are optional. The data types of each argument and its corresponding formal parameter must match. Parameters can be either: - a variable name (passed by reference, or by value) - a literal, constant or expression (passed by value)

 



Passing by Reference (default) - VB actually passes the memory address of the variable to the procedure. - Allows modifications to the variable to be passed back to the calling procedure.



Passing by Value (using ByVal keyword) - VB actually passes a copy of the value of the variable to the procedure. e.g. Function Square(ByVal NumValue As Long) as Integer

Cohesion and Coupling


Cohesion: degree of relationship between elements of a procedure - all the elements of a cohesive procedure should contribute to the performance of a single specific task. Coupling: degree of procedure independence - coupling is a measure of the extent of information interchange between procedures (aim for procedure independence). We should strive for high cohesion and low coupling. VB offers high cohesion in forms and class modules. VB does not enforce low coupling. To achieve low coupling: - use parameters rather than global variables for inter-procedure communication - do not reference objects on other forms by name - use property procedures (advanced topic) - encapsulate specific knowledge in class modules (advanced topic)



  

b0688454-8000-4686-aa20-1e43dba5c849.doc

54

Information Technology Studies

Programming in Visual Basic for Windows

13. Procedures (cont.) eg.1 - procedures Private Sub OutputInfo(N As String, A As Integer) 'Display a person‟s name and age in days Dim Days As Integer
„general „procedure

Days = A * 365 MsgBox "Hello " & N & " ,you are " & Days & " days old" End Sub Private Sub cmdNameAge_Click() 'Get name and age in whole years from user Dim Name As String Dim Age As Integer Name = InputBox("Enter Your Name") Age = Val(InputBox("Enter Your Age")) Call OutputInfo(Name, Age) End Sub
„event „procedure

eg.2 - functions Private Function Square(NumValue As Double) As Double „function is passed a number of type Double and „function returns the number multiplied by itself Square = NumValue * NumValue End Function

„user-defined „function

Private Sub txtNumber_Change() „event procedure „procedure calls a function called Square to square a number „note: this code could be behind a command button if desired! Dim Num As Double Dim Result As Double „get a real number from the user „store the function return value „convert to Double

Num = CDbl(Val(txtNumber.Text))

„Result = Sqr(Num) „first try a VB intrinsic Function „picResult.Print "Square Root of " & Num & " is " & Result Result = Square(Num) „then use our user-defined Function picResult.Print "The Square of " & Num & " is " & Result End Sub

b0688454-8000-4686-aa20-1e43dba5c849.doc

55

Information Technology Studies

Programming in Visual Basic for Windows

13. Procedures (cont.) eg.3 - another user-defined function Private Function CalcTax(Income As Currency) As Currency „function is passed an income and returns the tax payable Select Case Income Case Is < 5400 CalcTax = 0 Case Is < 20000 CalcTax = (Income - 5400) * 0.2 Case Is < 34000 CalcTax = 2920 + (Income - 20000) * 0.32 Case Else CalcTax = Income * 0.42 End Select End Function

eg.4 - and another user-defined function Private Function FindGrade(Score As Integer) As String „function receives a numeric score and returns grade as string Select Case Score Case 90 To 100 FindGrade Case 80 To 89 FindGrade Case 70 To 79 FindGrade Case 60 To 69 FindGrade Case 1 To 59 FindGrade Case Else FindGrade End Select End Function Private Sub txtScore1_KeyPress(KeyAscii As Integer) „event procedure passes txtScore1 to user-defined function above „to calculate the grade and assigns the grade string to a label. Dim Message1 As String „local variable to hold function result If KeyAscii = vbKeyReturn Then „if enter key is pressed Message1 = FindGrade(Val(txtScore1.Text)) „call function lblMessage1.Caption = Message1 „assign return value End If End Sub

= "A - Well done !" = "B - Good job !" = "C - You passed !" = "D - Do you need help ?" = "E - Please see me ..." = "Invalid Score, please re-enter"

b0688454-8000-4686-aa20-1e43dba5c849.doc

56

Information Technology Studies

Programming in Visual Basic for Windows

Student Notes (Topic 13)

b0688454-8000-4686-aa20-1e43dba5c849.doc

57

Information Technology Studies

Programming in Visual Basic for Windows

14. DATA MANIPULATION Working with Numbers


Numeric Expressions A numeric expression is any expression (comprising literals, variables, constants, array elements, function calls) that evaluates to a single numeric value (of data type Byte, Integer, Long, Single, Double, or Currency). eg. Sqr(Side1 - Side2) * 2.54 „return type is Double



Numeric Functions VB provides a host of numeric functions in a number of categories: Trigonometric Sin Cos Tan Atn Logarithmic Exp Log Conversion IsNumeric Val CByte CCur CInt CLng CSng CDbl Rounding Fix Int CInt Truncate to integer Round to lower integer Rounds .5 to nearest even integer Tests whether data can be converted to a number Converts a string to a number Converts a number to byte Converts a number to currency Converts a number to integer Converts a number to long integer Converts a number to single precision Converts a number to double precision Exponential Natural logarithm Sine of an angle Cosine of an angle Tangent of an angle Arctangent of an angle

b0688454-8000-4686-aa20-1e43dba5c849.doc

58

Information Technology Studies

Programming in Visual Basic for Windows

14. Data

Manipulation - Numeric Functions (cont.)

Random Numbers Randomize Rnd Seed random-number generator Generate a random number

Arithmetic Abs Sgn Sqr Absolute value Sign of a number Square root of a number

Financial Pmt IPmt PPmt FV PV NPer Rate NPV IRR MIRR SLN DDB SYD Amount of payments Interest payment Principle payment Future value Present value Number of periods Interest rate for period Net present value Interest rate of return Modified interest rate of return Straight-line method Double-declining balance method Sum-of-years' digits method

Date IsDate CDate Date Now DateDiff DateAdd DatePart Test whether data can be converted to a date data type Converts text data to a date data type Retrieves system date Retrieves system date and time Finds the difference between two dates Adds a specified time interval to a date Allows part of a date to be accessed

b0688454-8000-4686-aa20-1e43dba5c849.doc

59

Information Technology Studies

Programming in Visual Basic for Windows

14. Data Manipulation (cont.)


Type Conversion Whenever you assign a value of a particular data type to a variable of a different data type VB automatically tries to convert it. Type conversion can be numeric or string. VB even tries to convert from string to numeric or vice-versa. The following are perfectly legal: MyAge% = 39.9999 MyAge% = “23.67” Tax! = 23456 Value# = Cost& MySize$ = “Medium” YourSize$ = 38 „% is data type integer „ will round up to 24! „! is data type Single „# is data type double „& is data type Long „$ is data type String

The following causes a run-time error (Type mismatch): MyAge% = “Too much” Important: „ this string cannot be converted to an integer

Implicit type conversions are prone to errors. Avoid them if possible. Use the VB conversion functions instead.



Type Conversion During Variable Assignment Rounding Assigning a fractional number to a Byte, Integer or Long variable. eg. MyNum% = 34.84 BigNum! = -53411.5 Value& = BigNum! Print MyNum% Print Value& results in 35 -53412

„.5 rounds to closest even integer

Assigning a value of more than 7 significant digits to a single precision value. eg. Debt@ = 123456789 „@ is data type currency MyDebt! = Debt@ „or simpler MyDebt! = 123456789 Print MyDebt! results in 1.234568E+08 14. Data Manipulation - Type Conversion (cont.)
b0688454-8000-4686-aa20-1e43dba5c849.doc

60

Information Technology Studies

Programming in Visual Basic for Windows

Overflow Assigning a value outside the acceptable range of a variable. eg. MyNum% = 63111.5 MyNum! = 4.563D+75 results in a run-time error.

Precision Loss of precision can occur when assigning a single-precision value to a double-precision variable. eg. MyNum! = .11 YourNum# = MyNum! Print YourNum# results in only the first 7 digits (rounded) are valid .109999999403954


Type Conversion During Expression Evaluation At each operation in an arithmetic expression, the operands must be at the same level of precision. If necessary VB converts operands to the same level of precision from the less precise to the more precise. eg. TotalCost! = Num% * UnitCost! Num% is converted from integer to single-precision Type conversion during expression evaluation can result in: loss of accuracy eg. C# = 1000 Temp! = 5 / 1.5 Print Temp! * C# Print 5 / 1.5 * C# overflow eg. MyNum! = 2 * 25000 'greater than 32,767

'displays 3333.33325386047 'displays 3333.33333333333

b0688454-8000-4686-aa20-1e43dba5c849.doc

61

Information Technology Studies

Programming in Visual Basic for Windows

14. Data Manipulation - Type Conversion (cont.)


Numeric Conversion with the Variant Data Type When an expression contains a Variant variable, its data is evaluated the same as data in a numeric variable. Overflow, rounding, or loss of accuracy can still occur. Variant variables can be explicitly set to a particular data type. eg. Fee = CCur(RatePerHour! * BillingHour%) ensures that Fee contains data of type Currency (and not Single)



Testing Variables Before Converting A variable can be tested to see if it contains numeric data using the Is…functions. IsDate IsNumeric eg. If IsNumeric(UserInput) Then ... „process the number If Not IsDate(txtDate.Text) Then ... „notify the user test whether data can be converted to a date data type tests whether data can be converted to a numeric data type



Numeric Literals You can attach a type-declaration suffix to a numeric literal (but not recommended), this can be used to overcome some of the problems of loss of precision or overflow. eg. MyNum! = 2@ * 25000

The VB editor sometimes converts a literal to an alternate form containing a type-declaration suffix eg. type in: two! = 2.0 the editor converts the line to: Two! = 2#

b0688454-8000-4686-aa20-1e43dba5c849.doc

62

Information Technology Studies

Programming in Visual Basic for Windows

14. Data Manipulation - Working with Strings

Working with Strings


String Assignment stringvar = stringvalue stringvar and stringvalue can be fixed-length or variable-length 1. 2. If the length of the variable is greater than the value, space padding takes place If the length of the variable is less than the value, VB right truncates the value eg. Dim MyName As String Dim YourName As String * 6 MyName = “Rumplestiltsskin” YourName = MyName MyName = “Rumplestiltsskin” YourName = “Rumple” YourName = “Alf” Print YourName “Alf ” „variable-length „fixed-length „assignment „reassignment „no truncation „truncation „still fixed-length „blank padding

3. 4.

The maximum length of a string in VB is a bit less then 65,535 characters (64K) A Null string has length zero eg. MyText = “”

5. 6.

Strings are joined by using the ampersand operator (&) The plus operator (+), although syntactically correct, should be avoided.

b0688454-8000-4686-aa20-1e43dba5c849.doc

63

Information Technology Studies

Programming in Visual Basic for Windows

14. Data Manipulation - Working with Strings (cont.)


String Functions VB provides a host of string functions in a number of categories: (Note: the $ suffix on some functions indicates the function will return a string) Finding String Length Len Returns length of string

Converting Case LCase$ UCase$ Converts string to lowercase Converts string to uppercase

Returning a Substring Left$ Right$ Mid$ LTrim$ RTrim$ Trim$ Returns characters at far left Returns characters at far right Returns substring of a string Strips blanks from left of string Strips blanks from right of string Strips blanks from both ends of string

Converting to and from ANSI Asc Chr$ Returns ASCII value of a character Returns character from ASCII value

Converting between strings and numbers Val Str$ Hex$ Oct$ CInt CLng CSng CDbl CCur CByte CStr Converts string to number Converts number to string form Converts number to hex string Converts number to octal string Converts string to Integer number Converts string to Long number Converts string to Single number Converts string to Double number Converts string to Currency number Converts string to Byte Converts number to string form (also see Str Function)

b0688454-8000-4686-aa20-1e43dba5c849.doc

64

Information Technology Studies

Programming in Visual Basic for Windows

14. Data Manipulation - String Functions (cont.)

Converting Data Values to Formatted Strings Format$ Formats data values to strings

Searching for Substrings InStr Searches for substrings

Generating Strings String$ Space$ Constructs a string of identical characters Constructs a string of blank spaces

Comparing Strings StrComp Option Compare Compares two strings Sets case-sensitive comparison mode

Modifying a string variable (statements, not functions) Lset RSet Mid$ Left-justifies a string Right-justifies a string Merges one string with another



Advantages and Disadvantages of Variants Variant variables can manipulate both string and numeric data, and can convert easily back and forth. Advantages: Code can be written with a minimum number of functions and expressions (no need to convert data types). Code can be very hard to interpret. Logical errors in the code may be hidden because of automatic type conversions.

Disadvantages:

Recommendation:

Avoid the use of the Variant Data Type in your code.

b0688454-8000-4686-aa20-1e43dba5c849.doc

65

Information Technology Studies

Programming in Visual Basic for Windows

Student Notes (Topic 14)

b0688454-8000-4686-aa20-1e43dba5c849.doc

66

Information Technology Studies

Programming in Visual Basic for Windows

15. USING DATA FILES Types of Files Visual Basic supports three kinds of data files:

Sequential files Data stored as ASCII text (view with a text editor) Information is read from and written to file character by character (also field by field and record by record)

Random-Access files Data is stored in special Visual Basic internal formats Information is read from and written to record by record Requires a rigid file structure (fixed size records) Meets the needs of large database file applications

Binary files Data stored as individual bytes Information is read from, written to file byte by byte Allows saving of records of records of variable length No file structure exists / no internal format is assumed (Note: we will not be covering Binary files in this subject)

b0688454-8000-4686-aa20-1e43dba5c849.doc

67

Information Technology Studies

Programming in Visual Basic for Windows

15. Using Data Files (cont.) Manipulating Data Files Regardless of file type, to communicate with a disk file, a program must follow these essential steps:

1.

Open the data file Declares the name and path of the data file Establishes the file type, and the Input / Output (I/O) mode Opens a communication channel between the program and the file Associates an integer number with the data file, which is then used to reference the file in all later program instructions

2.

Read data from or Write data to the file (or do both) VB provides a variety of statements to perform I/O operations, depending on which type of file is being used

3.

Close the data file Disassociates the integer number from the data file Closes the communication channel between the program and the file

The File Pointer For each open file the operating system maintains an internal pointer to the current item of information being read / written. This pointer is automatically updated after each I/O operation. As a result, unless the file pointer is changed programmatically, the next I/O operation will start where the previous one finished. VB provides functions for reading and changing the file pointer.

b0688454-8000-4686-aa20-1e43dba5c849.doc

68

Information Technology Studies

Programming in Visual Basic for Windows

15. Using Data Files – Sequential Files Sequential Files Creating and Writing to a Sequential File 1. Open the file For Output Open filespec For Output As #filenum #filenum is an integer expression from 1 to 511 which is used to reference the file in later program instructions When you open a file For Output, VB will: eg. Open “C:\MYDATA.TXT” For Output As #2 The # is optional before the filenum parameter, but it is recommended Create it if the file does not exist Erase the contents if it already exists

Note: VB has a FreeFile function to obtain the next available file number, if required.

2.

Prepare the data Data can be entered into your program in several ways: - using assignment instructions - using text boxes - read data from other data files - computing data values using VB functions If needed, validate and convert the data to the correct data type before writing to a file.

b0688454-8000-4686-aa20-1e43dba5c849.doc

69

Information Technology Studies

Programming in Visual Basic for Windows

15. Using Data Files – Sequential Files (cont.) 3. Write the data Write #filenum, expressionlist Each Write instruction writes one record to the file Each expression in expressionlist is the data for one field of the record If you omit expressionlist, a blank line is written Write #2, “This is text for the first line”

4.

Close the file Close #filenum As in the open instruction, the # is optional Close terminates the association of the file number with the data file and can subsequently be reused Close #2

eg. In the following example the procedure GetInfo does the work of obtaining the information from somewhere (eg. the user) „Creating and Writing to a Sequential Data File Dim Year as Integer Dim Category as String Dim Value as Currency Dim Comment as String Open “C:\COINS\MYCOINS.TXT” For Output As #1 GetInfo(Year, Category, Value, Comment) Do While (Year <> 0) Write #1, Year, Category, Value, Comment GetInfo(Year, Category, Value, Comment) Loop Close #1

b0688454-8000-4686-aa20-1e43dba5c849.doc

70

Information Technology Studies

Programming in Visual Basic for Windows

15. Using Data Files – Sequential Files (cont.) Sample Input: Year 1910 1916 1935 Category Penny Half Penny Sixpence Value $70.00 $47.25 $200.00 Comment S mint mark, uncirculated Bought at auction for $75

Contents of output file (sequential text file): 1910, “Penny”, 70, “S mint mark, uncirculated” 1916, “Half Penny”, 47.25, “” 1935, “Sixpence”, 200, “Bought at auction for $75”

Appending to a Sequential File 1. Open the file For Append Open filespec For Append As #filenum 2. 3. Prepare the data (if necessary) Write the data Write #filenum, expressionlist 4. Close the file Close #filenum

Only the first step differs from the process of creating a new file.

Note: Opening a sequential file for output will always create a new file, ie. if the file already exits it will be totally overwritten by the newly created file, whereas append will add to an existing file if it exists, otherwise it will also create a new file if one doesn‟t exist.

b0688454-8000-4686-aa20-1e43dba5c849.doc

71

Information Technology Studies

Programming in Visual Basic for Windows

15. Using Data Files – Sequential Files (cont.) Reading from a Sequential File 1. Open the file For Input Open filespec For Input As #filenum 2. Read the data into the application Input #filenum, variablelist variablelist is a list of variables separated by commas You must know: - the number of fields in each record - the type of data in each field (data type) The variables in variablelist have to match the file data 3. 4. Process the data Close the file Close #filenum eg. „Reading and processing data from a Sequential Data File „eg. determine the total value of the coin collection Dim Dim Dim Dim Dim Year as Integer Category as String Value as Currency Comment as String TotalValue As Currency

Open “C:\COINS\MYCOINS.TXT” For Input As #1 TotalValue = 0 Do Until EOF(1) Input #1, Year, Category, Value, Comment TotalValue = TotalValue + Value Loop Close #1 MsgBox “Total Value is ” & Format$(TotalValue, “$0.00”)

b0688454-8000-4686-aa20-1e43dba5c849.doc

72

Information Technology Studies

Programming in Visual Basic for Windows

15. Using Data Files – Sequential Files (cont.) Sequential File Functions EOF(filenum) function tests whether the end of a sequential file has been reached. Do Until EOF(1) Always test for EOF before attempting a read Executing an Input# statement after the last record has already been read will result in a run time error (Input past end of file) Note: Several files can be opened simultaneously, as long as they have unique file numbers. Line Input #filenum, stringvar Reads an entire record into a single string variable eg. the first record in “C:\COINS\MYCOINS.TXT” is: 1910, “Penny”, 70, “S mint mark, uncirculated” and could be read with the following instruction: Dim MyData as String ... ... Line Input #1, MyData Input$(numchar, #filenum) Input(numchar, #filenum) Reads a specified number of characters from the current record. Input$ returns a string, while Input returns a variant eg. The following instruction reads the next 12 characters from the current record of file number 1 into the string variable NextDozen NextDozen = Input$(12, #1) LOF(filenum) Returns the number of bytes (length) of a data file. eg. MsgBox “Size of file 8 is ” & CStr(LOF(1))

b0688454-8000-4686-aa20-1e43dba5c849.doc

73

Information Technology Studies

Programming in Visual Basic for Windows

15. Using Data Files – Sequential Files (cont.) Print #filenum, expressionlist Writes data to a sequential file, similar to the Write statement, but does not output quotes around strings, or commas between fields.

Seek #filenum, position Sets the file pointer at the next byte you want to read or write. position specifies the file position as a byte in the range from 1 to 2,147,483,647 (Long Integer)

Seek(filenum) Returns the current file byte position.

Note: of the above file functions you will only need to know EOF and LOF for this subject.

eg.

Using a configuration file (Ted.ini)

Dim mConfigFile As String

„module level string variable „to store FilePath and FileName

b0688454-8000-4686-aa20-1e43dba5c849.doc

74

Information Technology Studies

Programming in Visual Basic for Windows

15. Using Data Files – Sequential Files (cont.)
Sub Form_Load() „ensure configuration file is in the application path and test „whether the path to the file is a parent or sub-directory Dim TempStr as String TempStr = App.Path If Right$(TempStr,1) <> “\” Then TempStr = TempStr & “\” End If mConfigFile = TempStr & “Ted.ini” „or could hard code file path but not recommended „mConfigFile = “A:\Ted.ini” frmTed.Show Call Blanktext
Call ReadConfigFile

End Sub Sub mnuFileExit_Click() „call procedure to save configuration file before exiting Call SaveConfigFile Unload frmTed End End Sub Sub ReadConfigFile() „check to see if configuration file exists and if found „open the file for reading into the application Dim Temp As String „or Variant!! Dim Index As Integer If Dir$(mConfigFile) = "" Then MsgBox "Config File not found - Using Defaults!" frmTed.BackColor = vbGreen For Index = 0 To 2 chkStyle(Index).Value = vbUnchecked Next Index
Else

Open mConfigFile For Input As #1 Input #1, Temp frmTed.Backcolor = Temp For Index = 0 To 2 Input #1, Temp chkStyle(Index).Value = Val(Temp) Next Index Close #1 End If End Sub Sub SaveConfigFile() „procedure opens a sequential file for output (for writing to) „therefore if the file already exists it will be overwritten Dim Index As Integer Open mConfigFile For Output As #1 Write #1, frmTed.BackColor For Index = 0 To 2 Write #1, chkStyle(Index).Value Next Index Close #1 End Sub

b0688454-8000-4686-aa20-1e43dba5c849.doc

75

Information Technology Studies

Programming in Visual Basic for Windows

15. Using Data Files – Random-Access Files Random-Access Files Random files offer three significant advantages over sequential files: 1. 2. 3. Two-way I/O activity: when opened, a random file can be read from and written to. Random-Access: individual records can be accessed quickly and conveniently. Record modification: you can modify individual records without rewriting all the other ones.

A disadvantage of Random-Access Files is that they will take up more disk space than Sequential and Binary files because the size of each record is fixed. Also, deleting records presents some difficulty. Creating a Random-Access File 1. Design the record Each record of a random file must have the same structure: the number of fields, data type of each field, and length of each field, cannot vary from record to record. eg. A Random-Access database for the coin collection: Field Year Category Value Comment Data Type Integer String * 20 Currency String * 50 No. Bytes 2 20 8 50 80

Total number of bytes per record:

2.

Define the Record Variable (user-defined data type): Type CoinType Year As Integer Category As String * 20 Value As Currency Comment As String * 50 End Type and dimension a variable of the above user-defined data type: Dim Coin As CoinType

b0688454-8000-4686-aa20-1e43dba5c849.doc

76

Information Technology Studies

Programming in Visual Basic for Windows

15. Using Data Files – Random-Access Files (cont.) Accessing a Random-Access File 1. Open the file For Random Access Open fspec For Random As #fnum Len = reclen „For Random‟ is at the same time Input, Output, and Append reclen is an integer specifying, in bytes, the size of each record For Random is the default, if omitted The # is optional before the fnum parameter eg. Open “MYCOINS.RAN” For Random As #1 Len = 80

or (this is better) Open “MYCOINS.RAN” As #1 Len = Len(Coin)

2.

Write a record Put #filenum, recordnum, variable If recordnum is omitted, the default is 1 eg. „writing a sample record to the coin database Coin.Year = 1910 Coin.Category = “Penny” Coin.Value = 70.0 Coin.Comment = “S mint mark, uncirculated” Put #1, 5, Coin „Write record number 5

3.

Read a record Get #filenum, recordnum, variable If recordnum is omitted, the default is the last record read, or written, plus one eg. „reading a sample record from the coin database Get #1, 5, Coin „Read record number 5

4.

Close the file Close #filenum

b0688454-8000-4686-aa20-1e43dba5c849.doc

77

Information Technology Studies

Programming in Visual Basic for Windows

15. Using Data Files – Random-Access Files (cont.) eg.1 Using and Updating a Random Access File

in the Declarations section of a code module: Type CoinType Year As Integer Category As String * 20 Value As Currency Comment As String * 50 End Type

then in the code section of the GUI form module: Option Explicit
'Random-Access File exercise written by Don Galvin

'declare module level variables Dim mCoin As CoinType Dim mCurRec As Integer Dim mEndRec As Integer

„user-defined data type „current record number „total number of records

Private Sub DisplayRecord(CurRec As Integer, LastRec As Integer) 'general procedure is passed references to mCurRec and mEndRec, gets current record from file, 'displays it on the form, and updates the caption property of the record number label. Get #1, CurRec, mCoin txtYear.Text = CStr(mCoin.Year) txtCategory.Text = mCoin.Category txtValue.Text = CStr(mCoin.Value) txtComment.Text = mCoin.Comment lblRecordCount.Caption = "Record " & CurRec & " of " & LastRec End Sub

b0688454-8000-4686-aa20-1e43dba5c849.doc

78

Information Technology Studies

Programming in Visual Basic for Windows

Using and Updating a Random Access File (cont.)
Private Sub cmdExit_Click() 'event procedure closes file, unloads form and exits the application Close #1 Unload frmCoin End End Sub Private Sub cmdNewRecord_Click() 'sets up form for entering a new record and updates record number counters txtYear.Text = "" txtCategory.Text = "" txtValue.Text = "" txtComment.Text = "" mEndRec = mEndRec + 1 mCurRec = mEndRec lblRecordCount.Caption = "Record " & mCurRec & " of " & mEndRec cmdNewRecord.Enabled = False „turn button off until record is saved txtYear.SetFocus End Sub Private Sub cmdSaveRecord_Click() 'event procedure saves (puts) the current record into the file mCoin.Year = CInt(Val(txtYear.Text)) mCoin.Category = txtCategory.Text mCoin.Value = CCur(Val(txtValue.Text)) mCoin.Comment = txtComment.Text Put #1, mCurRec, mCoin cmdNewRecord.Enabled = True „record saved, turn new button back on End Sub Private Sub cmdShowRecord_Click() 'event procedure allows the user to choose a record to be displayed Dim Msg As String Dim RecNum As Integer Msg = "What record do you wish to see ?" RecNum = CInt(Val(InputBox(Msg, "Show Record"))) If (RecNum > mEndRec) Or (RecNum <= 0) Then MsgBox ("Record number not found !") Else mCurRec = RecNum Call DisplayRecord(mCurRec, mEndRec) End If End Sub Private Sub cmdUpdate_Click() 'event procedure updates the value of the record collection by 10% Dim TempCoin As CoinType Dim Recordnum As Integer For Recordnum = 1 To mEndRec Get #1, Recordnum, TempCoin TempCoin.Value = TempCoin.Value * 1.1 Put #1, Recordnum, TempCoin Next Recordnum End Sub Private Sub Form_Load() 'event procedure opens the random file, determines the number of records 'in the file and updates the caption property of the record counter label Open "A:\coin.rnd" For Random As #1 Len = Len(mCoin) mEndRec = LOF(1) / Len(mCoin) „determine no. of records in file mCurRec = 0 „set the current record to zero? lblRecordCount.Caption = "Record " & mCurRec & " of " & mEndRec End Sub b0688454-8000-4686-aa20-1e43dba5c849.doc

79

Information Technology Studies

Programming in Visual Basic for Windows

15. Using Data Files – Random-Access Files (cont.) Other Random-Access File Functions Seek #filenum, position Sets the file pointer at the next record you want to read or write position specifies the file position as a record in the range from 1 to 2,147,483,647 (Long Integer) For random files, Seek (and Loc) deal with record numbers, not bytes eg. The following statement moves the pointer to the 23rd record of file number 9: Seek #9, 23 After this Seek, a Get or Put instruction without a recordnum parameter operates on this newly reset file position. Put #9, , Coin Loc(#Filenum) Returns the current position in the file ie. returns record number of last record read or written in the file. Note: for this subject you should not need to use the above two functions.

eg.2

A Random-Access File Application (VBCARD.VBP)

See code for VBCARD on the student network.

b0688454-8000-4686-aa20-1e43dba5c849.doc

80

Information Technology Studies

Programming in Visual Basic for Windows

15. Using Data Files – Binary Files Binary Files Note: we will be concentrating on working with Sequential and Random-Access Files in this subject, you will not be required to use Binary Files.  Binary files are files that are interpreted byte by byte.  Useful when interpreting files created in formats alien to VB, such as spreadsheets, or non-ASCII word-processing documents.  A file pointer is associated with each binary file which identifies which byte is the next to be read or written.  You can both read and write to a file after it is opened in binary mode.

Working with a Binary File 1. Open the file for Binary Open filespec For Binary As #filenum File is opened for reading, writing and appending eg. Open “C:\MYFILE.BIN” For Binary As #3

2.

Read data Get #filenum, startbyte, variable startbyte is a numeric expression specifying the byte in the file where I/O begins If startbyte is omitted, the default is the current file pointer. Subsequent Get and Put instructions automatically adjust this pointer Get reads the necessary number of bytes required to satisfy the length of variable (For a variable-length string its length is considered to be that of the data currently stored in it) eg. Reading into a double-precision variable (ie. 8 bytes) Get #3, ,MyData# „Read next 8 bytes

The file pointer is automatically advanced 8 bytes

b0688454-8000-4686-aa20-1e43dba5c849.doc

81

Information Technology Studies

Programming in Visual Basic for Windows

15. Using Data Files – Binary Files (cont.) 3. Write data Put #filenum, startbyte, variable Put is used to modify existing data, or write new data past the end of the file eg. Put #3, 45, MyName Put #3, , Coin „writes starting at byte 45 „writes coin record at current location

4.

Close the file Close #filenum

Other Binary File Functions Seek #filenum, pointer Sets the file pointer to the next byte you want to read or write For binary files, Seek (and Loc) deal with bytes, not record numbers eg. The following statement moves the pointer to the 41st byte of file number 2: Seek #3, 41 After this Seek, a Get or Put instruction without a startbyte parameter operates on this newly reset file position. Put #3, ,Coin

b0688454-8000-4686-aa20-1e43dba5c849.doc

82

Information Technology Studies

Programming in Visual Basic for Windows

Student Notes (Topic 15)

b0688454-8000-4686-aa20-1e43dba5c849.doc

83

Information Technology Studies

Programming in Visual Basic for Windows

16. ARRAYS Array Syntax Dim arrayname[(LBound To ]Ubound) As type eg. Dim Students(1 To 20) As Integer Dim CountArray(99) As Integer Dim Matrix(1 To 10, 1 To 20) As Long NOTE: Default is Option Base 0

Working with Arrays Array variables allow you to store multiple data values under a common name. Array variables can contain data values (Byte, Boolean, Int, Lng, Sng, Dbl, Date, Cur, Str, Var, or user defined type), controls, forms, and objects. Array variables consist of a name and index number (subscript). eg. Value = Cost(30) „Literal number

Cost is the name of the array, 30 is its index number (subscript). Subscripts can be any numeric expression (ie. single value) Salary(EmployeeNo) Cost (23 + Num) Cost((Num1 – Num2) * 3) „Variable name „Simple expression „Compound expression

Arrays must be declared so that VB does not confuse them with functions eg. Result = Sqr(16) Value = Cost(30) „Sqr is a VB function „Cost is a variable array

Dim arrayname([sublow To]subhigh) As Type [sublow To ]subhigh establishes the lowest and highest values allowed for the array subscript If sublow is omitted, 0 is used as the lowest value. This default can be changed to 1 by: Option Base 1

b0688454-8000-4686-aa20-1e43dba5c849.doc

84

Information Technology Studies

Programming in Visual Basic for Windows

16. Working with Arrays (cont.) Array Type can be: Byte Boolean Integer Long Single Double Date Currency String String * num Variant User-defined (ie. array of records)

eg. Dim Dim Dim Dim Dim Dim Dim Dim Dim Client(200) As String „base 1 or 0 ? Profit(1975 To 1993) As Single Shares(-40 To 15) As Long Tax(30), Cost(30) „not recommended A%(45), B%(34), C$(21) „not recommended StudentScores(1 To 20) As Integer StudentNames(1 To 20) As String CoinCollection(1 to 100) As CoinType „user-defined LastName(1 To MAX_RUNNERS) As String „note constant

A subscript value outside the defined range will cause a “Subscript out of Range” run-time error. eg. Option Base 1 Dim Client(200) As String Client(0) = “Mr.Smith” Client(201) = “Mr.Jones” „out of range „out of range

Scope of Array Declarations Follow the same rules as ordinary variables, as follows. 1. Entire project: declare in Declarations section of a code module eg. Public arrayname([sublow To ]subhigh) As type the array is then available to every procedure in the entire project. 85

b0688454-8000-4686-aa20-1e43dba5c849.doc

Information Technology Studies

Programming in Visual Basic for Windows

16. Working with Arrays - Scope of Array Declarations (cont.) 2. Entire code module: declare in Declarations section of a code module eg. Dim arrayname([sublow To ]subhigh) As type

3.

Entire form module: declare in Declarations section of a form module eg. Dim arrayname([sublow To ]subhigh) As type

4.

Within a code module, or form module, procedure: declare inside the procedure (ie. locally) eg. Sub subname Dim [Static] arrayname([sublow To]subhigh) As type . . . End Sub or, Static Sub subname Dim arrayname([sublow To ]subhigh) As type . . . End Sub Arrays declared with Dim within a procedure are local to the procedure. Arrays within a procedure may be declared Static (or declared within a Static procedure). Arrays created with Static are persistent arrays whose values are kept in memory after the procedure is finished running. You may also choose to create a dynamic array at the procedure level using ReDim. These values are lost after the procedure is finished running... more later. eg. ReDim arrayname([sublow To ]subhigh) As type

b0688454-8000-4686-aa20-1e43dba5c849.doc

86

Information Technology Studies

Programming in Visual Basic for Windows

16. Working with Arrays - Scope of Array Declarations (cont.) eg. 1 Using a Table Lookup (POSTCODE.VBP)

Postcode.txt (sequential file) 2000,”Sydney” 3000,”Melbourne” 4000,”Brisbane” 5000,”Adelaide” nnnn,”Your Postcode” Dim PostCode(1 to 10) As Integer Dim Suburb(1 to 10) As String Dim mCount As Integer „array of post codes „array of suburbs „count file records

Sub Form_Load() „read data from disk into two arrays mCount = 0 „initialise counter Open App.Path & "\postcode.txt" For Input As #1 Do Until EOF(1) „loop until EOF mCount = mCount + 1 „count file records Input #1, PostCode(mCount), Suburb(mCount) Loop Close #1 txtPostCode.Text = "" txtSuburb.Text = "" End Sub Sub txtPostCode_Change() „find suburb corresponding to Post Code Dim Message As String Dim Index As Integer Message = "No such post code found" For Index = 1 To mCount „is a For Loop best here? If Val(txtPostCode.Text) = PostCode(Index) Then Message = Suburb(Index) „corresponding position End If Next Index txtSuburb.Text = Message End Sub

b0688454-8000-4686-aa20-1e43dba5c849.doc

87

Information Technology Studies

Programming in Visual Basic for Windows

16. Working with Arrays (cont.) Using Two-Dimensional Arrays Two-dimensional arrays represent tabular data with a row and column structure (eg. a spreadsheet). Dim arrayname([sublow To ]subhigh, [sublow To ]subhigh) As type You need two subscripts to specify an element of a two-dimensional array - one subscript for the row number and one subscript for the column number (ie. declare Rows first then Columns). eg.1 „setting up a chess board Dim Piece(1 To 8, 1 To 8) As String For Row = 1 To 8 For Column = 1 To 8 Piece(Column, Row) = “None” Next Column Next Row Piece(3,5) = “White Pawn” ... ... Piece(6,7) = “Black Knight” eg.2 „a game of noughts and crosses Dim TicTacToe(1 To 3, 1 To 3) As String * 1 TicTacToe(1,1) = “X” TicTacToe(2,2) = “O” ... ... TicTacToe(1,3) = “X” „row 1, column 1 „row 2, column 2 „row 1, column 3

X O

X

Visual Basic Allows arrays with as many as 60 dimensions! eg. a 3-dimensional array of type Currency: Dim Profit(1 To 5, 1 To 12, 1 To 31) As Currency All dimensions of a multi-dimensional array must be of the same data type.

b0688454-8000-4686-aa20-1e43dba5c849.doc

88

Information Technology Studies

Programming in Visual Basic for Windows

16. Working with Arrays (cont.) Array Functions  Find the lowest or highest subscript for a dimension of an array: Lbound(arrayname [, dimension]) as Integer Ubound(arrayname [, dimension]) as Integer default dimension is 1. Sub BlankArray(ParArray() as String) „sets all the array elements to null (“”) Dim i as Integer For i = Lbound(ParArray) to Ubound(ParArray) ParArray(i) = “” Next i End Sub  Create and initialize array values. Array(paramlist) This function returns a variant as an array: Dim Wk as Variant Wk = Array(“S”,”M”, “T”, “W”, “T”, “F”, “S”) MsgBox Wk(3)  Erase the contents of an array. You reset an array with Erase statement. Erase arrayname[, ...] If arrayname refers to a fixed array each element is initialised as follows: numerics variable-len strings fixed-len strings variant to to to to 0 null string “” ASCII 0 Empty „ will display “W”

If arrayname refers to a dynamic array, the array is de-allocated, freeing the memory used by the array: eg. Static MyArray(1 to 1000) As Integer MyArray(500) = 18 Print MyArray(500) Erase MyArray Print MyArray(500) Output is: 18 0 89

„resets to 0

b0688454-8000-4686-aa20-1e43dba5c849.doc

Information Technology Studies

Programming in Visual Basic for Windows

Arrays - Fixed (Static) and Dynamic Memory Allocation Memory location of stored variables can be allocated by VB in two ways: 1. 2. When program starts - fixed allocation (more efficient ??) While program is running - dynamic allocation (more flexible and more memory efficient)

With dynamic allocation storage is allocated and de-allocated while the program runs. If a dynamic variable is no longer needed, the memory is released. With fixed allocation storage is allocated before the program runs and memory remains allocated throughout the execution of the program. Array Memory Allocation  An array dimensioned with literal (or constant) subscripts uses fixed allocation. eg. Dim MonthlyProfit(1 To 12) as Currency Const MAX_ITEMS As Integer = 520 Dim Invoices(1 To MAX_ITEMS) as Integer  „fixed allocation „fixed allocation

An array dimensioned with a missing subscript uses dynamic allocation. eg. Dim Students() As Integer „dynamic allocation

The array dimension (size) can then be allocated with a ReDim statement. ReDim Statement  You allocate a dynamic array with ReDim statement. ReDim arrayname(subscriptrange) [As type] eg. ReDim Students(1 To 15)  „array allocation

You can reallocate a dynamic array repeatedly by executing further ReDim statements. ReDim [Preserve] arrayname(subscriptrange) ReDim de-allocates the old array and reallocates the array with the new dimensions. All the old array values are lost during the process unless Preserve is specified. eg. ReDim Students(1 To 20) ... ReDim Preserve Students(1 To 20) „array redimensioned „array values retained



When using Preserve, ReDim cannot change the number of dimensions and can only change the size of the last dimension.

b0688454-8000-4686-aa20-1e43dba5c849.doc

90

Information Technology Studies

Programming in Visual Basic for Windows

16. Working with Arrays (cont.) Passing Arrays to Procedures   Pass the array name and an empty set of parentheses. Inside the called procedure / function you can use the Lbound and Ubound functions to determine the lower and upper bounds of the array Lbound(arrayname [, dimension]) Ubound(arrayname [, dimension]) eg.1 Average = FindAverage(MyArray()) Private Function FindAverage(AnyArray() As Integer) As Single 'function is passed an array of integers, calculates total, and returns average Dim Index As Integer „for loop control variable Dim Count As Integer „count array elements Dim Sum As Integer „store the total For Index = LBound(AnyArray) To UBound(AnyArray) Count = Count + 1 „increment Count Sum = Sum + AnyArray(Index) „sum the array values Next Index If Count = 0 Then „test for zero elements FindAverage = 0 Else FindAverage = Sum / Count „function return value End If End Function eg.2 Sub Form_Load () Static Sales(1 To 8, 0 To 10) As Integer ... ... „set values for array elements ... Print “Total Sales = ”; SumArray(Sales()) End Sub Function SumArray (A() As Integer) As Integer „function returns the sum of a 2 dimensional array Dim Total As Integer, Num1 As Integer, Num2 As Integer Total = 0 For Num1 = LBound(A, 1) To UBound(A, 1) For Num2 = LBound(A, 2) To UBound(A, 2) Total = Total + A(Num1, Num2) Next Num2 Next Num1 SumArray = Total End Function
b0688454-8000-4686-aa20-1e43dba5c849.doc

91

Information Technology Studies

Programming in Visual Basic for Windows

17. USING RECORDS  These are user-defined data types, and are combinations of standard data types. eg.1 defined: Type CoinType Year As Integer Category As String * 20 Value As Currency Comment As String * 50 End Type declared: Dim Coin As CoinType eg.2 defined: Type EmployeeRecord Name As String * 50 Pay As Double End Type declared: Public gEmployee As EmployeeRecord      Also referred to as a user-defined data type, combination data type, or structure. Allows custom design of an individualised data type for a particular application. Like an array, a record is a structured data type made up of multiple elements. Unlike an array, elements of a record can be different data types. Records may be declared as Private in Form Modules or Public in Code Modules. Defining a Record [Public / Private] Type recordname elementname As type elementname As type ... End Type type can be a fundamental data type, an array, another user-defined type.

b0688454-8000-4686-aa20-1e43dba5c849.doc

92

Information Technology Studies

Programming in Visual Basic for Windows

17. Using Records (cont.) eg. Type Employee FullName As String * 35 IDNumber As Integer Salary As Currency End Type Type Committee ProjectName As String * 30 Chairman As Employee Treasurer As Employee MonthlyBudget(1 To 12) As Currency End Type Dim President As Employee Dim UrbanRenewal As Committee Dim Council(1 To 10) As Committee President.FullName = “Whitney Crabtree” President.IDNumber = 1000 President.Salary = 823.18 UrbanRenewal.Chairman = President Print UrbanRenewal.Chairman.Fullname Print UrbanRenewal.Chairman.IDNumber Print UrbanRenewal.Chairman.Salary ‟35 bytes ‟2 bytes ‟8 bytes

‟30 bytes ‟45 bytes ‟45 bytes ‟96 bytes

‟45 bytes ‟216 bytes ‟2160 bytes

Output is: Whitney Crabtree 1000 823.18

b0688454-8000-4686-aa20-1e43dba5c849.doc

93

Information Technology Studies

Programming in Visual Basic for Windows

17. Using Records (cont.) The following examples are included to demonstrate programming concepts that include record structures (user-defined data types), passing records as parameters, and arrays of records. When you wish to hold the same information for a set of data, you can define the fields as part of a record. The record is defined in VB as a Type statement Type CollegeData Name As String * 30 State As String * 2 YearFounded As Integer End Type The record can contain different types of fields, but all string fields must be fixed length fields, so that the record has a fixed length. Type declarations are made in a standard module (.BAS module). A variable of the type is declared when required by Dim College As CollegeData The fields are referenced as college.name, college.state, college.yearFounded Many different variables can be declared as type CollegeData. Individual fields can be set, or the whole of a variable an be copied by assigning one variable to another of the same type. Relational operators will only work with the individual fields. e.g. Dim College as CollegeData Dim University as CollegeData College.Name = “Adelaide” College.State = “SA” College.YearFounded = 1994 `set individual fields

University = College University.Name = “Adelaide Uni” User Defined Record Types can be used as arguments to functions and procedures. Type CollegeData Name As String * 30 State As String * 2 YearFounded As Integer End Type

b0688454-8000-4686-aa20-1e43dba5c849.doc

94

Information Technology Studies

Programming in Visual Basic for Windows

17. Using Records (cont.) Sub cmdRecordDemo_Click() „Demonstrate use of records Picture1.Cls Dim college As collegeData Call GetDat(college) Call DisplayStatement(college) End Sub Sub DisplayStatement(school As collegeData) Dim century As Integer, when As String century = 1 + Int(school.yearFounded / 100) Picture1.Print RTrim(school.name); " was founded in the" & Str(century); Picture1.Print "th century in "; school.state Dim university As collegeData university.name = "M.I.T." university.state = "MA" university.yearFounded = 1878 If school.yearFounded < university.yearFounded Then when = "before " Else when = "after " End If Picture1.Print RTrim(school.name); " was founded "; Picture1.Print when; RTrim(university.name) End Sub Sub GetDat(school As collegeData) school.name = Text1.Text school.state = Text2.Text school.yearFounded = Val(Text3.Text) End Sub

eg.1 - Arrays of Record Types can be defined and used (egrec1.vbp)

b0688454-8000-4686-aa20-1e43dba5c849.doc

95

Information Technology Studies

Programming in Visual Basic for Windows

17. Using Records (cont.) Option Explicit Type Postcodedata suburb As String * 20 postcode As Integer End Type Dim postdata(1 to 1000) As Postcodedata Dim PcodeNO As Integer Sub Form_Load() 'Read data from disk into arrays Open app.Path & "\postcode.seq" For Input As #1 PcodeNO = 0 Do Until EOF(1) PcodeNO = PcodeNO + 1 Input #1, postdata(PcodeNO).postcode, postdata(PcodeNO).Suburb Loop txtPostCode.Text = "" txtSuburb.Text = "" Close #1 End Sub Sub txtPostCode_LostFocus() 'Find suburb corresponding to Post Code Dim Message As String Dim j As Integer Dim inPostcode As Integer txtSuburb.Text = "" inPostcode = Val(txtPostCode.Text) If Len(txtPostCode.Text) = 4 Then 'ignore unless length is 4 j = 1 'loop through array looking for match Found = False do while (not Found and j<PcodeNO) j = j + 1 Found = (inPostcode = postdata(j).postcode) loop If (Found) then Message = postdata(j).Suburb else Message = "No such post code found" End If txtSuburb.Text = Message 'display suburb End If End Sub

b0688454-8000-4686-aa20-1e43dba5c849.doc

96

Information Technology Studies

Programming in Visual Basic for Windows

17. Using Records (cont.) Arrays of Record Types can be passed as arguments to procedures. (egrec2.vbp)

Option Explicit Dim postdata(1 To 1000) As Postcodedata Dim pcodeno As Integer Sub Form_Load() Dim filename As String filename = app.path & “\postcode.seq" 'load arrays in procedure Call LoadArrays(postdata(), filename) txtPostCode.Text = "" txtSuburb.Text = "" End Sub Sub LoadArrays(pdata() As Postcodedata, ByVal filename As String) 'Read data from disk into array of records Open filename For Input As #1 pcodeno = 0 Do Until EOF(1) pcodeno = pcodeno + 1 Input #1, pdata(pcodeno).postcode, pdata(pcodeno).suburb Loop Close #1 End Sub

b0688454-8000-4686-aa20-1e43dba5c849.doc

97

Information Technology Studies

Programming in Visual Basic for Windows

17. Using Records (cont.) Function SearchPostcodeArray(pdata() As Postcodedata, target As _ Integer, maxelems As Integer) As Integer Dim found As Integer Dim index As Integer found = False index = LBound(pdata) Do While index <= maxelems And found = False If target = postdata(index).postcode Then found = True End If index = index + 1 Loop If found = True Then SearchPostcodeArray = index - 1 Else SearchPostcodeArray = -1 End If End Function Sub txtPostCode_Change() txtSuburb.Text = "" End Sub Sub txtPostCode_LostFocus() 'Find suburb corresponding to Post Code Dim Message As String Dim index As Integer 'ignore unless length is 4 If Len(txtPostCode.Text) = 4 Then index = SearchPostcodeArray(postdata(), Val(txtPostCode.Text), pcodeno)' set default message If index = -1 Then Message = "No such post code found" Else Message = postdata(index).suburb End If 'display suburb txtSuburb.Text = Message End If End Sub

b0688454-8000-4686-aa20-1e43dba5c849.doc

98

Information Technology Studies

Programming in Visual Basic for Windows

Student Notes (Topics 16 and 17)

b0688454-8000-4686-aa20-1e43dba5c849.doc

99

Information Technology Studies

Programming in Visual Basic for Windows

18. WORKING WITH FILES File and Directory Management Functions Summary of functions available to manipulate files and directories: Keyword ChDir ChDrive FileCopy MkDir RmDir CurDir GetAttr Dir FileDateTime FileLen Kill Name SetAttr Action Change directory or folder. Change the drive. Copy a file. Make directory or folder. Remove directory or folder. Return current path. Return file, directory, label attributes. Return file name or volume label. Return file date/time stamp. Return file length. Delete a file Rename a file, directory, or folder. Set attribute information for a file

eg. make a backup file (copy), delete original file, and rename backup file FileCopy “A:\Test.txt”, “A:\Test.bak” Kill “A:\Test.txt” Name “A:\Test.bak” As “A:\Test.txt” some further examples : 1. 2. 3. 4. 5. MkDir “B:\CLIENTS” NewDir$ = “B:\CLIENTS” RmDir NewDir$ ChDrive “C” ChDrive “dog” ChDir “B:\CLIENTS” Kill “C:\VB” „cannot kill directories Kill “C:\VB\*.BAK” „wildcards permitted FName = "TESTFILE.DAT" DirName = "\TEMPDIR" Kill DirName & "\" & FName FName1 = "OLDFILE.DAT" FName2 = "NEWFILE.DAT" DirName = "\TEMPDIR" Name Fname1 As FName2 Name Fname1 As DirName & "\" & FName2 „note the quotation marks „only interprets the first char „note the quotation marks

6.

b0688454-8000-4686-aa20-1e43dba5c849.doc

100

Information Technology Studies

Programming in Visual Basic for Windows

18. Working with Files - File and Directory Maintenance Functions (cont.) 7. 8. FileCopy “C:\HOMES.FRM”, “A:\VBHOMES.FRM” Dim MyFileDtTm As String MyFileDtTm = FileDateTime(“C:\HOMES.FRM”) Print MyFileDtTm „will print 19:30:20 HomeDir$ = CurDir$(“cdrive”) 'only 1st char

9. 10.

Dim FName As String FName = Dir$("C:\*.*", vbDirectory) Print FName Do While FName <> "" FName = Dir$ 'get next filename Print FName Loop
Note: Dir$ returns the first filename that matches the path and filename, then Dir$ with no arguments will return the next file matching path and filename, otherwise returns a zero length string.

11.

To find the volume label of the c drive: Dim s as String s = “Your C: drive is “ & _ Dir$(“c:\*.*”, vbVolume) MsgBox s The file attribute information is manipulated via a bit mask according to the following table: Attribute Normal file Read-Only file Hidden file System file Volume label MS-DOS directory Archived file GetAttr Value 0 1 2 4 8 16 32 Constant vbNormal vbReadOnly vbHidden vbSystem vbVolume vbDirectory vbArchive

12.

eg. If GetAttr(“ABC.FRM”) And vbNormal Then.. „ file, directory or volume label SetAttr(“C:\HOMES.FRM”, vbReadOnly) Note individual attribute values can be added together
eg.

-> System and Read-Only -> Directory and Read-Only 18. Working with Files (cont.)
b0688454-8000-4686-aa20-1e43dba5c849.doc

(5) (17)

101

Information Technology Studies

Programming in Visual Basic for Windows

Common Dialog Control (revisited)   Provides a standard set of dialog boxes, as common to most windows applications. Displayed by using one of the following methods: Method ShowOpen ShowSave ShowColor ShowFont ShowPrinter ShowHelp  Type of Dialog Box Displayed File Open Save As Colour Font Print Invokes Windows Help file

The following instruction displays a File Save dialog box: dlgMyDialog.ShowSave Filtering of file types to be displayed in a File Save or File Open Dialog Box can be achieved by assigning a value to the filter property of the Common Dialog Control. eg. to list all files with a .doc extension we could set the following filter: dlgMyDialog.Filter = "Doc Files (*.doc) | *.doc"



The following instruction displays a File Open dialog box: dlgMyDialog.ShowOpen eg. Private Sub mnuFileOpen_Click() Dim MyFile As String „store the filename Dim Temp As String „hold the file data dlgMyDialog.Filter = "Text Files (*.txt) | *.txt" dlgMyDialog.ShowOpen 'File Open Dialog Box MyFile = dlgMyDialog.filename If Dir$(MyFile) = "" Then „file not found txtTed.Text = "File not found" Else „file is found Open MyFile For Input As #1 Input #1, Temp „read from file txtTed.Text = Temp „assign value Close #1 End If End Sub

b0688454-8000-4686-aa20-1e43dba5c849.doc

102

Information Technology Studies

Programming in Visual Basic for Windows

Data Validation


Testing data before assigning to variables, or writing it to files Data can be tested to see if it contains numeric data using the Is…functions: IsDate IsNumeric eg. test whether data can be converted to a date data type tests whether data can be converted to a numeric data type

If IsNumeric(UserInput) Then ... „process the number If Not IsDate(txtDate.Text) Then... „notify the user

Do you think there is a requirement for an IsString function? Once data has been tested and confirmed to contain the right type of data it should then be converted to the correct data type before assignment, using the VB intrinsic conversion functions (ie. CByte, CCur, CInt, CLng, CSng, SDbl, CDate).


An example of using a Boolean Function for Data Validation Private Function ValidCoinValue(MyValue As String) As Boolean „function is passed a text box string and returns true if data is null or numeric, else false Dim MsgString As String „store message string Dim MsgType As Integer „type of MsgBox Dim MsgTitle As String „title of MsgBox Dim Response As Integer „required for MsgBox function If MyValue = "" Then „OK if a null string ValidCoinValue = True ElseIf IsNumeric(MyValue) Then „OK if a number ValidCoinValue = True Else „else data not OK MsgType = vbExclamation MsgTitle = "Data Entry Error" MsgString = MyValue & " incorrectly entered" Response = MsgBox(MsgString, MsgType, MsgTitle) ValidCoinValue = False End If End Function „before assigning user input data to variables or files first test and validate the type of data, „note this example only validates the type of data, it does not include any range validation! If ValidCoinValue(txtValue.Text) = True Then mCoin.Value = CCur(Val(txtValue.Text)) „assign to variable Else txtValue.SetFocus „user to re-enter End If

b0688454-8000-4686-aa20-1e43dba5c849.doc

103

Information Technology Studies

Programming in Visual Basic for Windows

Student Notes (Topic 18)

b0688454-8000-4686-aa20-1e43dba5c849.doc

104

Information Technology Studies

Programming in Visual Basic for Windows

19. PROGRAM ERRORS There are three fundamental types of errors that can occur: 1. 2. 3. Syntax Errors Run-time Errors Logic Errors

Syntax Errors
 

When an instruction does not follow VB rules. Syntax errors can be: misspelt keyword improper punctuation combine keywords incorrectly incorrect parameter passing eg. Prnt "Hello" Exit Loop A = Sqr(B, C) ' misspelling ' should be Exit Do ' too many parameters



Syntax errors are usually trapped by the editor, or found when the program is loading, or when the sequence of code containing the error is compiled in order to be executed. Use the Tools/Options/General/Compile on demand option to force VB to compile the entire project before loading.



Run-Time Errors
 

When VB cannot perform a program instruction Run-time errors can be: - divide by zero - reading a file that does not exist - etc. etc. eg. Sub cmdErrors_Click() Dim NumHits As Integer, NumAB As Integer Dim Msg As String NumHits = Val(InputBox$("No. of hits?")) NumAB = Val(InputBox$("Times at bat?")) Msg = "Batting average is " & NumHits / NumAB MsgBox Msg End Sub

If NumAB is zero the above example will produce a "Divide by Zero" run-time error.

b0688454-8000-4686-aa20-1e43dba5c849.doc

105

Information Technology Studies

Programming in Visual Basic for Windows

19. Program Errors (cont.)


When a run-time error occurs VB suspends execution and displays the following screen:

If Debug selected: VB enters Break mode and highlights the offending line of code (and all current values of variables, within context, are retained in memory). Examine the Err Object in VB Help to see Error Numbers and ErrorStrings, ie. trappable errors.

Logic Errors
 

When the program does not produce the correct results Logic errors are the most difficult to locate start by looking for the obvious reasonable looking output can be wrong verify VB is actually doing what you want, eg . Int() rounds to lower integer, not nearest integer . double-clicking a mouse triggers a Click as well as a DblClick event. make sure that your algorithms are correct use VB's extensive debugging features Sub ShowCost () Dim NumItems As Integer Dim UnitCost As Currency NumItems = 50 UnitCost = 6.95 Print "Total Cost ="; UnitCost / NumItems End Sub Output (including a logic error) from the above is: Total Cost = .139

eg.

b0688454-8000-4686-aa20-1e43dba5c849.doc

106

Information Technology Studies

Programming in Visual Basic for Windows

19. Program Errors (cont.) Error Handling


Error trapping lets an application intercept a run-time error and pass control to an error handling routine Without error trapping the application simply aborts with a VB error message To enable error trapping: 1. 2. 3. On Error Resume Next On Error GoTo linenumber On Error GoTo label

 



Once an error trap has been set, it remains enabled until execution of the procedure ends as a result of: 1. 2. 3. 4. Exit Sub Exit Function End Sub End Function

or, until the error trap is disabled by: 5.


On Error GoTo 0

To return from an error handler: 1. 2. 3. 4. 5. Resume Resume 0 Resume Next Resume linenumber Resume label (very dangerous!) (as above!) (be careful!) (old hat!) (way to go!)

b0688454-8000-4686-aa20-1e43dba5c849.doc

107

Information Technology Studies

Programming in Visual Basic for Windows

19. Error Handling (cont.)

Resuming from an Error Handler
Start

On Error GoTo Error Handler

Action 1 (Error)

Resume

Action 2

Resume Next

GoHere: Action 3

Resume GoHere

End

eg. Sub Form_Resize () 'the world's simplest error handler Dim NiceTry As Single On Error GoTo ErrorHandler NiceTry = 1 / 0 MsgBox "No way to get here" Exit Sub ErrorHandler: MsgBox "I think you made a boo-boo" Exit Sub 'could also try Resume Next End Sub



without an On Error statement a run-time error occurs and the application aborts with a Divide by Zero error message box with an On Error statement the error is trapped and remains under program control to take whatever corrective action is necessary



b0688454-8000-4686-aa20-1e43dba5c849.doc

108

Information Technology Studies

Programming in Visual Basic for Windows

19. Error Handling (cont.) We should always use error trapping when working with files: eg.1 Sub ReadConfigFile(ConfigFile as String) Dim FileNum as Integer FileNum = FreeFile 'get next file number On Error GoTo MyErrorHandler Open ConfigFile For Input As #FileNum ... 'file processing + error checks ... 'only close file if we opened it! Close #FileNum MyExit: Exit Sub 'the only exit point is here MyErrorHandler: MsgBox "Could not open file '" & _ ConfigFile & "' - " & Error Resume MyExit 'note - only one exit point End Sub Sub ReadConfigFile(ConfigFile as String) Dim FileNum as Integer FileNum = FreeFile 'get next file number On Error Resume Next 'be careful with this statement Open ConfigFile For Input As #FileNum If Err > 0 Then 'if any error MsgBox "Could not open file '" & _ ConfigFile & "' - " & Error Else ... 'file processing + error checks ... 'only close file if we opened it! Close #FileNum End If End Sub

eg.2

The above 2 procedures will not crash the program if the file can not be opened / created:

Always give the user as much feedback as possible in error messages!

Note:Error Handling will be covered in greater detail in the advanced VB programming subject.

b0688454-8000-4686-aa20-1e43dba5c849.doc

109

Information Technology Studies

Programming in Visual Basic for Windows

20. SYSTEM OBJECTS These are global objects, which are predefined by VB. Each have specific properties and methods which can be accessed at run-time. There are five system objects: 1. 2. 3. 4. 5. Application Debug Clipboard Printer Screen

The App Object. Contains information about the application Methods none Property EXEName Path Title HelpFile PrevInstance Major, Minor eg. Meaning Meaning Executable filename, with no extension. Pathname to the application. Windows Task Manager caption Name of Help file, if any Tests if app currently running? Version control information

Sub cmdApplicationInfo_Click() Print "Program Name is "; App.EXEName Print "Path is "; App.Path Print "Title is "; App.Title Print "Version is "; App.Major; "."; App.Minor End Sub

Debug Object Sole purpose is to permit the display of information in the Debug (immediate) window at run time. Methods Print Properties none eg. Meaning Display information in Debug window at run time Meaning

Sub cmdDebug_Click() Debug.Print “Program Name is “; App.EXEName Debug.Print “Path is “; App.Path Debug.Print “Title is “; App.Title End Sub

b0688454-8000-4686-aa20-1e43dba5c849.doc

110

Information Technology Studies

Programming in Visual Basic for Windows

20. System Objects (cont.)

Clipboard Object Provides direct access to the Windows Clipboard Methods SetText GetText Clear GetData SetData GetFormat Properties none Meaning Send text data to the Clipboard Get text data from the Clipboard Clear contents of the Clipboard Get picture data from the Clipboard Send picture data to the Clipboard test if Clipboard has data of a particular format Meaning

eg. Form1.Print Clipboard.GetText Printer Object Provides direct access to a printer (by default it refers to the system printer as specified in the Window Control Panel). Methods Circle EndDoc KillDoc Line NewPage Print PaintPicture Zoom Properties CurrentX CurrentY eg. Meaning Draws a circle, ellipse, or arc Terminates a document sent to the printer Resets the print job if possible Draws lines and rectangles Ends current page and advances to the next Prints text string using current colour and font Prints an image from a file to the printer Scales the printed output (percent) Meaning Determines the current horizontal position Determines the current vertical position

Printer.CurrentX = 0 „at left of paper Printer.CurrentY = 2000 „2000 twips from top Printer.FontItalic = True „print in italic Printer.Print “This appears on the printer.” Printer.Print „print a blank line „changing the printer Set Printer = Printers(2) Printer.Print “This will go to “; Printer.Print Printer.DeviceName Printer.EndDoc

b0688454-8000-4686-aa20-1e43dba5c849.doc

111

Information Technology Studies

Programming in Visual Basic for Windows

20. System Objects (cont.)

Screen Object References the entire video screen Methods none Properties ActiveControl ActiveForm FontCount Fonts(Index) Height MousePointer TwipsPerPixelX TwipsPerPixelY Width Meaning Meaning Specifies the control that has the focus Specifies the form that is the active window Specifies the number of fonts available Specifies all the font names available The height of the screen Determines the type of mouse pointer Specifies the no. of twips per pixel, horizontally Specifies the no. of twips per pixel, vertically The width of the screen

eg.1

„display the text of the active control Sub Form_Click () If TypeOf Screen.ActiveControl Is TextBox Then lblControl.Caption = Screen.ActiveControl.Text Else lblControl.Caption = "Button: " & _ Screen.ActiveControl.Caption End If End Sub

eg.2

„centres the active form on the screen Public Sub CentreForm(MyForm as Form) „declare in Code Module MyForm.Left = (Screen.Width - MyForm.Width) / 2 MyForm.Top = (Screen.Height - MyForm.Height) / 2 End Sub Private Sub Form_Load() Me.Show Call CentreForm(Me) End Sub „declare in the active form „show the active form (Me) „call procedure to centre form

b0688454-8000-4686-aa20-1e43dba5c849.doc

112

Information Technology Studies

Programming in Visual Basic for Windows

Student Notes (Topics 19 and 20)

b0688454-8000-4686-aa20-1e43dba5c849.doc

113

Information Technology Studies

Programming in Visual Basic for Windows

APPENDIX VB Naming Conventions
Using naming conventions is one of those little things that makes reading source code much easier and more enjoyable. This list was compiled from the VB manuals and white papers provided from Microsoft. These naming conventions are provided as guide lines for programmers to standardise and decode the structure and logic of an application. To provide readable and unambiguous variable names. Also to be consistent with other language conventions (most importantly the VB programmers guide and standard Windows Hungarian C) . Controls Prefix ani bed cbo chk clp cmd(3d) com ctr dat db dir dlg drv ds fil frm fra gau gpb grd hed hsb img ink key lbl lin lst mdi mpm mps mc mnu opt ole opt out pic pnl rpt shp spn txt tmr vsb Control Type Description Animation button Pen Bedit Combobox and dropdown Listbox Checkbox Picture Clip Command Button (3D) Communications Control (Used within procs) Data ODBC Database Directory List Box Visual Basic Pro Common Dialog Drive List Box ODBC Dynaset File List Box Form Frame Gauge Group Push Button Grid Pen Hedit Horizontal Scroll Bar Image Pen Ink Keyboard key status Label Line Listbox MDI Child Form MAPI Message MAPI Session MCI Menu Option Button Ole Client Option Button Outline Control (VB3) Picture 3d Panel Report Control (VB3) Shape (circle, square, oval, and rectangle) Spin Control Text/Edit Box Timer Vertical Scroll Bar

b0688454-8000-4686-aa20-1e43dba5c849.doc

114

Information Technology Studies

Programming in Visual Basic for Windows

VB Naming Conventions (cont.)

Variables Prefix b c d db ds dt td f h i l n s u ul vnt w a g m st v r VB Type % @ # Variable Use Description Boolean Currency - 64 bits Double - 64 bit signed quantity Database Dynaset Date+Time TableDef Float/Single - 32 bit signed floating point Handle Index Long - 32 bit signed quantity Integer (sizeless, counter) String Unsigned - 16 bit unsigned quantity Unsigned Long - 32 bit unsigned quantity Variant (big and ugly to discourage use) Word - 16 bit signed quantity Array Global (recommended) Local to module or form (recommended) Static variable Variable passed by value (local to a routine) Variable passed by reference (local to a routine)

variant ! % % & %, &, or # $ & # %

Menu Names Menu Handler Name mnuHelpContents mnuFileOpen mnuFormatCharacter mnuFileSendFax mnuFileSendEmail Menu Caption Sequence Help.Contents File.Open Format.Character File.Send.Fax File.Send.Email

Recommendations: Always use the above VB naming convention when naming objects, controls and menu structures. All Public (global) variables should be prefixed with g and all module level variables should be prefixed with m. Other naming conventions for variables are a matter of personal style and are therefore optional.

b0688454-8000-4686-aa20-1e43dba5c849.doc

115


				
DOCUMENT INFO
Jun Wang Jun Wang Dr
About Some of Those documents come from internet for research purpose,if you have the copyrights of one of them,tell me by mail vixychina@gmail.com.Thank you!