Introduction to Visual Basic 6.0Visual basic is a Microsoft windows programming language. Programs written in visual basic are done in an Integrated Development Environment (IDE). The IDE allows a programmer to:
Create/design a user interface. Code the program. Set the properties for the controls. Run/compile the program. Debug the program.
Terms used in visual basic Program
A set of instructions that are aimed at accomplishing a certain task. Properties
These are characteristics of objects in a program. Controls
They are elements that you place inside a form to create the user interface.
Methods These are actions or function associated with the objects in visual basic.
Events These are responses to actions performed by programs.
THE VISUAL BASIC IDEThe IDE is where the programmer creates and tests projects in visual basic.
The form windowThis is where the programmer designs the user interface for data entry and navigation.
Project explorer windowIt holds all the filenames the makes up your project.
Properties windowUsed to set properties of objects on a form. They are attributes of controls.
Toolbox Holds buttons that you use to create the user interface. Each buttons represents a control.
Form layout windowSpecifies the form position at run time.
ToolbarsContains shortcut buttons for frequently used operations. Each button represents a command.
TOOLBOX CONTROLS Textbox - txt
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
1
A control for accepting user input. Label – lbl
A control that displays unedited text to the user. Command button – cmd
A control which represents a button. The user clicks on it initiate an action.
Picturebox – picA control that displays images.
Frame – fraA control that is used to group objects.
Checkbox – chk A control that provides user with a toggle choice.
Listbox – lstA control that provides a list of items
Combobox – cboA control that provides a short list of items.
Data – datA control for connecting to a database.
OLE – oleA control for interacting other windows applications.
Shape – shpA control that is used to draw circles,rectangles.
VARIABLESVariables are memory locations that hold values to be used by the program at execution time. It is a valid identifier.
Rules for creating variables Variables cannot be keywords in visual basic. Variables must begin with letters. The maximum length of variable names is 255 characters. Variable names can contain letters, numbers and underscores.
Variables categories Static variables
They are those variables that don’t change when the program executes. Dynamic variables
They are those variables that change when the program executes.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
2
Types of variables Global variables
These are variables that are accessible through the program when it executes.
Local variables They are programs that are accessible within the function or procedures in which they are declared.
NB: the keyword Dim is used to declare dynamic variables in visual basic. The keyword const is used to declare static variables in visual basic.
DATA TYPES A data type shows the kind information or data a certain variable stores.
IntegerStores whole numbers ie non-floating numbers.
Boolean Represents true or false values.
Byte Stores a byte of information.
Double Represents adouble precision floatingpoint numbers.
Single Represents a single precision floating point numbers.
Strings Stores a series of characters.
Variant Stores data types of any type.
Date and time.Stores date and time formats.
Long Stores whole numbers with greater magnitudes.
Currency Stores monetary values.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
3
Data type Bytes Range Integer 2 -32768 to 32768Byte 1 0 to 255Currency 8 -922337203685477 to 922337203685477Date/Time 8 1 January 100 to 31 December 9999Double 8 -1.79769313486232E308 to 1.79769313486232E308Long 4 -2147483648 to 2147483648Boolean 2 True or FalseObject 4 Any object type.Single 4 -3.40823E38 to 1.44012998E-45String 10+ 0 to 20,000,000,000Variant 16 Any value within the range listed above.
Example 1Write a program that calculates the sum of two integers
Algorithms Start Enter the integer values. Compute the sum the two numbers. Produce results Stop
Flowchart
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
4
Start
Enter the two integers
Compute the sum of the two integersThe sum of the two integers
Stop
Interface
Code
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
5
Private Sub cmdcompute_Click()Dim num1 As IntegerDim num2 As IntegerDim sum As Integernum1 = Val(txtnum1.Text)num2 = Val(txtnum2.Text)txtsum.Text = Val(txtnum1.Text) + Val(txtnum2.Text)End Sub
ARITHMETICS IN VISUAL BASIC Visual basic allows programmers to do mathematical operations using various arithmetic operators. Vb operator Arithmetic operator Algebraic expression Vb expression Addition + X+y X+ySubtraction - a-b x-8Multiplication
* Yb Y*b
Division / u/v u/vDivision(integer)
\ None u\v
Exponentiation
^ qp Q^p
Negation - -e -eModulus Mod Qmodr qmodr
ORDER OF PRECEDENCE These are visual basic arithmetic rules that determine the sequence of evaluating values in a visual basic expression.
Rules Use the operators in order of precedence. For operators on the same precedence, evaluate from left to right in an expression.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
6
Order of precedence Symbol Operator 1 ( ) The value between the brackets2 ^ The exponentiation3 - Negative (negative values)4 * / Multiplication and division5 \ Integer division6 Mod Remainder division 7 + - Addition and subtractionLastly & String concatenation
Example 1Evaluate the expression below
Total=10+15*2/4^2Total=10+15*2/16Total=10+30/16Total=10+1.875Total=11.875
Example 2Number= (8-5)*3^2Number=3*3^2Number=3*9Number=27
Example 3X= (8-5*3) ^2X= (-7) ^2X=49
Example 4Number= ((8-5)*3) ^2Number= (3*3) ^2Number=9^2Number=81
Visual basic reserved words
AndAlso Ansi As Assembly
Auto Boolean ByRef Byte
ByVal Call Case Catch
CBool CByte CChar CDate
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
7
CDec CDbl Char CInt
Class CLng CObj Const
CShort CSng CStr CType
Date Decimal Declare Default
Delegate Dim DirectCast Do
Double Each Else ElseIf
End Enum Erase Error
Event Exit False Finally
For Friend Function Get
GetType GoSub GoTo Handles
If Implements Imports In
Inherits Integer Interface Is
Let Lib Like Long
Loop Me Mod Module
MustInherit MustOverride MyBase MyClass
Namespace New Next Not
Nothing NotInheritabl
e
NotOverridable Object
On Option Optional Or
OrElse Overloads Overridable Overrides
ParamArray Preserve Private Property
Protected Public RaiseEvent ReadOnly
ReDim REM RemoveHandler Resume
Return Select Set Shadows
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
8
Shared Short Single Static
Step Stop String Structure
Sub SyncLock Then Throw
To True Try TypeOf
Unicode Until Variant When
While With WithEvents WriteOnly
Xor Const ExternalSource #If...Then...#Else
Add AddHandler AddressOf Alias And
AndAlso Ansi AppActivate As Asc
AscW Assembly Auto Beep Boolean
ByRef Byte ByVal Call CallByName
Case Catch CBool CByte CChar
CDate CDbl CDec Char ChDir
ChDrive Choose Chr CInt Class
Clear CLng Close CObj Command
Const Count CreateObject CShort CSng
CStr CType CurDir Date DateAdd
DateDiff DatePart DateSerial DateString DateValue
Day DDB Decimal Declare Default
Delegate DeleteSetting
Description Dim Dir
Do Double Each Else ElseIf
End Enum Environ EOF Erase
Erl Err Error ErrorToString
Event
Exit ExternalSource
False FileAttr FileCopy
FileDateTime FileGet FileLen FileOpen FilePut
FileWidth Filter Finally Fix For
FormatCurrency
FormatDateTime
FormatNumber FormatPercent
FreeFile
Friend Function FV Get GetAllSettings
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
9
GetAttr GetChar GetException GetObject GetSetting
GetType GoTo Handles HelpContext
HelpFile
Hex Hour If IIf Implements
Imports In Inherits Input InputBox
InputString InStr InStrRev Int Integer
Interface IPmt IRR Is IsArray
IsDate IsDBNull IsError IsNothing IsNumeric
IsReference Item Join Kill LastDllError
LBound LCase Left Len Let
Lib Like LineInput Loc Lock
LOF Long Loop LSet LTrim
Me Mid Minute MIRR MkDir
Mod Module Month MonthName
MsgBox
MustInherit MustOverride
MyBase MyClass Namespace
New Next Not Nothing NotInheritable
NotOverridable
Now NPer NPV Number
Object Oct On Option Optional
Or OrElse Overloads Overridable
Overrides
ParamArray Partition Pmt PPmt Preserve
Print PrintLine Private Property Protected
Public PV QBColor Raise RaiseEvent
Randomize Rate ReadOnly ReDim Region
Rem Remove RemoveHandler Rename Replace
Reset Resume Return RGB RmDir
Rnd RSet RTrim SaveSetting
Seek
ScriptEngine ScriptEngine ScriptEngine ScriptEngine
Second
BuildVersion MajorVersion
MinorVersion Select Set
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
10
SetAttr Shadows Shared Shell Short
Single SLN Source Space Spc
Split Static Step Stop Str
StrComp StrConv StrDup String StrReverse
Structure Sub Switch SYD SyncLock
SystemTypeName
Tab Then Throw TimeOfDay
Timer TimeSerial TimeString TimeValue To
Today Trim True Try TypeName
TypeOf UBound UCase Unicode Unlock
Until Val Variant VarType VbTypeName
WeekDay WeekDayName
When While With
WithEvents Write WriteLine WriteOnly Xor
Visual basic input output commands
Mathematics
Round - Rounds a number to a selectable number of decimal places o result = round ( tempvariable,2 )
Val - Returns the numerical content of a string o result = Val ("123.4")
Int - Returns an integer by truncating (different than Fix) o i = int ( tempvariable )
Fix - Returns an integer by truncating (different than Int) o i = fix ( tempvariable )
Hex - Returns the hexadecimal value of any number o temp$ = hex ( tempvariable )
Oct - Returns the octal value of any number o temp$ = oct ( tempvariable )
Tan - Returns the tangent of an angle o tempvariable1 = tan ( tempvariable2 )
Rnd - Returns a random number between 0 and 1 o tempvariable1 = rnd
Randomize - Initializes the Rnd function so it gives different answers each time
o randomize Sgn - Returns the sign of a number
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
11
o i = sgn ( tempvariable ) Sin - Returns the sine of an angle
o tempvariable1 = sin ( tempvariable2 ) Cos - Returns the cosine of an angle
o tempvariable2 = cos ( tempvariable ) Abs - Converts a number to a positive value
o i = abs ( tempvariable ) Sqr - Returns the square root of a number
o tempvariable1 = sqr ( tempvariable2 ) Log - Returns the base 10 logarithm of a number
o tempvariable1 = log ( tempvariable2 ) Atn - Returns the arctangent of an angle
o tempvariable1 = atn ( tempvariable ) Partition - Sort of an oddball function but segregates values according to
ranges o
Type Conversions - A variety of conversion functions o CBool, CByte, CCur, CDate, CDbl, CDec, CInt, CLng, CSng, CStr,
CVar
Strings
Left - Returns the left n characters of a string o temp$ = left$ ( teststring$, 4 )
Right - Returns the right n characters of a string o temp$ = right$ ( teststring$, 4 )
Trim - Removes leading and trailing spaces of a string o temp$ = trim$ ( teststring$ )
LTrim - Removes only the leading spaces of a string o temp$ = ltrim$ ( teststring$ )
RTrim - Removes only the trailing spaces of a string o temp$ = rtrim$ ( teststring$ )
UCase - Makes all characters upper case o temp$ = ucase$ ( teststring$ )
LCase - Makes all characters lower case o temp$ = lcase$ ( teststring$ )
Mid - Returns n characters from a string, starting a any position o temp$ = mid$ ( teststring$, 1, 4 )
Len - Returns the length of a string (how many characters it has) o temp$ = len ( teststring$ )
LSet - Positions a string inside another, flush to the left o temp$ = lrset ( teststring$ )
RSet - Positions a string inside another, flush to the right o temp$ = rset$ ( teststring$ )
Format - Returns a string formatted according to a user-defined format o temp$ = format$ ( teststring$, "####.0" )
String -
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
12
o temp$ = left$ ( teststring$, 4 ) Chr - Returns the string representation of a number
o temp$ = str$ ( 32 ) Asc - Returns the ASCII code of a single character
o temp$ = asc ( "A" ) Space - Returns n spaces
o temp$ = space$ ( 15 ) Instr - Determines if one string is found within a second string
o i = Instr (starthere, string1, string2) InStrRev - Determine if one string is found in a second, starting at the
end o i = InStrRev (string1, string2, start)
StrComp - Compares two strings o result = StrComp (string1, string2)
StrConv - Converts the case of a string's characters o StrConv (string, vbuppercase)
StrReverse - Reverses character order in a string o StrReverse (string1)
Replace - Replaces each occurrence of a string o Replace (bigstring, searchstring, replacementstring)
FormatCurrency - Returns a string using a currency format o FormatCurrency(var1, 2)
FormatDateTime - Returns a date or time expression o FormatDateTime("3/2/99",vbShortTime)
FormatNumber - Returns a number formatted according to a variety of options
o FormatNumber(var1, 2) FormatPerCent - Returns a number formated as a percent
o FormatPerCent(var1, 2)
Arrays
Option Base - Determines whether the lowest range of an array is 0 or 1 o option base 1
Erase - Erases all values of an array o erase (arrayname)
Dim - Creates an array o dim arrayname(25)
Redim - Resets the bounds of an array (has option to save values) o redim arrayname(28)
UBound - Returns the upper dimension of an array o i = ubound (arrayname)
LBound - Returns the lower dimension of an array o i = lbound (arrayname)
Filter - Returns a subset of an array based on a filter o Filter (inputarray, searchstring)
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
13
Array - Yes, there is a function called array. It returns an array that has been filled with data from a list. It allows you to put the actual data values in the code to avoid having the user input it or to avoid having to read it from a file
o ArrayName = Array (10, 20, 30) Join - Concatenates strings within an array
File Handling (Generic)
Dir - Returns a filename that matches a pattern o temp$ = Dir ("*.*")
CurDir - Returns the current directory o temp$ = CurDir
MkDir - Creates a directory o mkdir ( "newdirectoryname" )
ChDir - Changes the current directory to a new location o chdir ( "newdirectoryname" )
ChDrive - Changes the current drive o ChDirve "A"
RmDir - Removes the indicated directory o rmdir ( "directoryname" )
Freefile - Returns an unused file handle o i = freefile
Open - Opens a file for access, locking it from other applications o open "filename" for input as #1
Close - Closes a file so that other applications may access it o close #1
LOF - Returns the length of a file in bytes o i = lof ( #1 )
EOF - Returns a boolean value to indicate if the end of a file has been reached
o statusvariable = eof ( #1 ) Name As - Renames a file
o name "filename1" as "filename2" Kill - Deletes a file
o kill "filename" Fileattr - Returns attribute information about a file
o i = int ( tempvariable ) GetAttr - Returns attributes of a file or directory
o i = GetAttr("c:\windows\temp") SetAttr - Sets the attributes of a file
o SetAttr pathname, vbHidden Reset - Closes all disk files opened by the OPEN statement
o Reset FileDateTime - Returns data file was created or last edited
o FileDateTime ( filename ) FileLen - Returns length of file in bytes
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
14
o FileLen ( filename ) FileCopy - Copies a file to a new name
o FileCopy sourcefile, destinationfile Lock - Controls access to a part or all of a file opened by OPEN
o Lock #1 UnLock - Restores access to a part or all of a file opended by OPEN
o UnLock #1 Width # - Set the output line width used by the OPEN statement
o Width #2, 80
File Handling - ASCII-specific
Line Input - Reads an entire line of ASCII text o line input #1, tempvariable$
Write - Puts data in a file, with separators for the data o write #1, tempvariable$
Print - Puts data in a file with no separators o print #1, tempvariable$
Spc - Used in a print statement to move a number of spaces o Print #2, var1; spc(15); var2
Tab - Used in a print statement to move to TAB locations o Print #2, var1; Tab(20); var2
File Handling - Binary-specific
Get - Reads data from a file o get #1, anyvariable
Put - Puts data into a file o put #1, anyvariable
Seek - Moves the current pointer to a defined location in a file o seek #1, 26
Input o input #1, anyvariable
Loc - Returns current position with an open file o i = Loc(#2)
Declarations
Dim - Used to define a variable as a certain type o i = dim i as integer, r as single o You can use the Option Explicit to make sure that VB forces you to
declare every variable you use. DIM is that simplest way to declare a variable
ReDim - Used to change the dimensions of a dynamic array o redim arrayname(37)
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
15
o Don't be afraid of this one. You can use ReDim to create an array whose size grows by 1 every time you want to add a number to it. Then, the UBound tells you how many numbers you've added.
Static - Establishes a procedure variable which keeps its value between calls
o static i as integer o For example, if you want to keep track of how many times you've
been in a procedure, set a counter as STATIC and increment it by one for each visit to the procedure. It will never go away until the program is terminated.
Public - Creates a variable which can be accessed outside its own procedure
o public i as integer o Even if you're the only programmer writing code in your
application, use of Private vs Public will help catch errors if you inadvertently try to access an out-of-scope variable
Private - Creates a variable that can be read only in its own procedure or module, according to where the declaration took place.
o private i as integer o Use this as often as possible to avoid unnecessary exposure of your
variables to coding mistakes. Sub - Defines a procedure which can execute a block of code
o Sub NewProcedure (var1 as integer, var2 as string) o Be sure to check out HELP for how to handle Sub arguments.
There are more questions and mistakes made concerning the use of arguments than just about anything else I've seen.
Function - Declares a procedure which can return a value o Function NewFunction (var1 as integer, var2 as string) as SINGLE o This is actually the most versatile of the Sub/Function procedure
types. It can do anything a Sub can do as well as returning a value for use in an expression.
Call - Transfers control to a Sub or Function (is optional) o Call Procedure 1 o Since the use of CALL is optional, forget you ever saw it
CallByName - Executes a method of an object or set/returns a property o CallByName(form1,procedurename,vbMethod) o The really cool thing about this is that you don't have to hardcode a
procedure call. Just use a string variable with the name of the procedure to call.
Option Explicit - Instructs VB to force an explicit declaration of all variables
o Option Explicit o You're borderline stupid if you don't use it to catch typing errors.
Set up the VB IDE to automatically include this in all projects. Option Compare - Instructs VB on how to make string comparisons
o Option Compare Binary
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
16
o This can add case-insensitivity for those times when you don't want to hard-code it
Option Private - Prevents a module's content from being referenced outside a project.
o Option Private Module o Generally doesn't apply to most VB applications. If you find a good
use for it let me know. Property Get - Declares how to get the value of a property
o Property Get Name() o You won't use this much until you get into creating classes of your
own Property Let - Declares how to assign a value to a property
o Property Let Name() o You won't use this much until you get into creating classes of your
own Property Set - Declares how to set a variable reference to an object
oo You won't use this much until you get into creating classes of your
own Set - Assigns an object reference to a variable
o Set X = form1.txtInputFromUser o Very useful for making code more readable or simply to cut down
on how much typing you have to do! Let - Precedes assignment of a value to a variable
o Let i = 3 o It's optional, no one uses, so forget you ever saw it
Type...End Type - Creates a user defined part type which consists of standard VB data types
o type anytypename o one as string o two as integer o three as boolean o End Type o This is a really excellent way to keep several kinds of data under
one variable name. Plus, you can PUT or GET a user-defined type with a single line of code.
Const - Creates a variable whose value is fixed o const anyname o Basically, use this to give easy to remember names to values. For
example, suppose you use the value 37.2 a lot in your code, then if you put CONST MyAge = 37.2 in your code you'll be able to insert the MyAge where the 37.2 should have gone. Easier to type and easier to read. Also, you can chane the value of the constant by changing only the declaration line of code, rather than searching out every place the value was used!
Declare - Used to define a procedure that exists in another file o declare functionname (arg1 as integer, arg2 as string) as integer
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
17
oo ArrayName = Array (10, 20, 30) o Implements - Specifies a class to be implemented in a module
o Friend - Allows procedure to be callable from modules outside the
class
o GetObject - Return a reference to an ActiveX component
o CreateObject - Creates and returns a reference to an ActiveX object
o GetAutoServerSettings - Returns information about the state of an
ActiveX component's registration.
o Enum - Declares a type for an enumeration
o Event - Declares a user-defined event
o TypeName - Returns the type of data in a variable
o VarType - Returns the type of data in a variable
o DefType - Sets the default data type of variables DefInt A-Z
o IS - A variety of data type or status checking options IsArray, IsBindable, IsBroken, IsDate, IsDirty, IsEmpty,
IsError, IsMissing, IsNull, IsNumber, IsObject, IsReady, IsRootFolder
Date/Time Date - Gets the current date Time - Gets the current time Now - Gets the current date and time Timer - Returns the number of seconds since midnight DateAdd - Adds a time interval to a date DateDiff - Returns how many time intervals there are between two dates DateSerial - Returns the month/day/year DateValue - Returns the date Year - Returns the current year Month - Returns the current month (integer) MonthName - Returns the text of the name of a month Day - Returns the current day Hour - Returns the current hour
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
18
Minute - Returns the current minute Second - Returns the current second TimeSerial - Returns a date with the hour/minute/second TimeValue - Returns the time WeekDay - Returns the current day of the week (integer) WeekDayName - Returns the text of a day of the week
MsgBox - A built-in dialog box that gives a message and allows a user input
i = msgbox "Read this!", vbokonly, "Test Message" DoEvents - Allows VB to complete pending tasks
doevents Shell - Executes a 2nd program from within the current program
shell "notepad.exe" Note - VB does not wait for the Shell'd program to quit before
executing the next line of code! Command - Gives any text that followed a VB .EXE execution command
temp$ = command Environ - Returns the system environmental space content
temp$ = environ Beep - Makes the computer beep once.
beep InputBox - A built-in dialog box that allows entry of a text string
inputbox "Input a value!", 5 AddressOf - Provides an entry point for an external program to use a
procedure AddressOf ( procedurename )
AppActivate - Activates an applications window AppActivate ( windowtitle )
RaiseEvent - Fires an event declared at module level RaiseEvent ProcedureName
Load - Load an object load form1
Unload - Unload an object Unload form1
LoadPicture - Load a picture into a control property form1.picture = loadpicture (filename)
SavePicture - Save a picture to a file SavePicture(form1.picture,filename)
LoadResData - Load the data from a resource file LoadResData(index,format)
LoadResString - Load a string from a resource file LoadResString(index,format)
SendKeys - Send keys to another app as though they were from the keyboard
Sendkeys {DOWN} QBColor - Returns a value corresponding to the original QB values 0-15
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
19
form1.backcolor = QBcolor (12) RGB - Returns a color value by inputting the red, green, and blue parts
form1.backcolor = RGB (12,128,256) Me - Refers to the current object, usually the active form
print Me.caption
GetSetting - Get a value from the Registry temp$ = getsetting "TestApp", "SectionName", "KeyName",
"defaultvalue" GetAllSettings -Returns a list of key settings and their values
GetAllSettings(appname,section) SaveSetting - Save a value into the Registry
savesetting "TestApp", SectionName, KeyData DeleteSetting - Deletes an entry from the registry
deletesetting "TestApp", "SectionName", "Keyname"
Program compiling
This involves a process of testing a program in visual programming to check if the program is error free. It is a process of converting a program from source code to its object equivalent.
Program debugging
This is a process of correcting errors in a program. When a program executes in visual programming, it must produce the expected results. If it doesn’t give the expected output then it has errors. In this regard the programmers should start the process of debugging.
Testing programs in visual programming
This is a process of running (executing) programs to find errors (bugs). The process of finding bugs is called debugging as mentioned above. Program testing is part of the procedure which ensures that the program corresponds
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
20
with original program specification and that it works in the intended environment.
Test plan
These are the stages involved in testing the programs. They include the following.
1. Deskchecking
After writing the program the programmer goes through the program on a paper to eliminate any error that might cause extra work later.
2. Translator system checking
After coding the program is checked using the compiler or translator to detect any syntax error. The programmer corrects these errors and then resubmits the program to the compiler until the errors are over.
3. Program run with test data
These are trial runs done with test data that includes all variations and extremes data including data with errors to ensure that program does not grind to an halt if incorrect data is used.
4. Diagnostic procedures
For complex programs diagnostic procedures are used to find logical errors. A trace routine print the results at each stage to enable errors detected quickly. If the trace routine is not available, the programmer can insert instructions in the program to print out intermediate results at key points.
5. System test with actual data (full-scale) system
Usually new system are run parallel with existing system for a short period so that the results are compared and adjustments made.
TEST DATA
This is the information that is used to test the new system or program. The program tried and executed at least once every routine through the program and the accuracy of the program is verified to meet the original design specification.
Categories of test data
Dummy data
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
21
This is the data input into a system for trial purposes. Used to test the system for correctness.
Real data (normal data)
This includes the general data for which the system was designed.
Exceptional data
Programs are designed to accept certain range of data. If illegal data is input it should be able to detect and reject it rather than try to process it to avoid getting wrong results.
Visual operators basic Expressions
An operator is a code element that performs an operation on one or more code elements that hold values. Value elements include variables, constants, literals, properties, returns from Function and Operator procedures, and expressions.
An expression is a series of value elements combined with operators, which yields a new value. The operators act on the value elements by performing calculations, comparisons, or other operations.
Types of Operators
Visual Basic provides the following types of operators:
Arithmetic Operators: perform familiar calculations on numeric values, including shifting their bit patterns.
Comparison Operators: compare two expressions and return a Boolean value representing the result of the comparison.
Concatenation Operators: join multiple strings into a single string.
Logical Operators: In Visual Basic combines Boolean or numeric values and return a result of the same data type as the values.
Assignment operator: assign variables to some values in visual basic for example equal sign (=)
Evaluation of Expressions
The end result of an expression represents a value, which is typically of a familiar data type such as Boolean, String, or a numeric type.
The following are examples of expressions.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
22
X=5 + 4
Y=15 * System.Math.Sqrt (9) + x
"Concat" & "ena" & "tion"
763 < 23
Several operators can perform actions in a single expression or statement, as the following example illustrates.
x = 45 + y * z ^ 2
Types in Visual Basic 6
• No matter how hard we try, errors do creep into our programs. These errors can be grouped into three categories:
1. Syntax errors2. Run-time errors
3. Logic errors
Syntax errors occur when you mistype a command or leave out an expected phrase or argument. Visual Basic detects these errors as they occur and even provides help in correcting them. You cannot run a Visual Basic program until all syntax errors have been corrected.
Run-time errors are usually beyond your program's control. Examples include: when a variable takes on an unexpected value (divide by zero), when a drive door is left open, or when a file is not found. Visual Basic allows you to trap such errors and make attempts to correct them.
Logic errors are the most difficult to find. With logic errors, the program will usually run, but will produce incorrect or unexpected results. The Visual Basic debugger is an aid in detecting logic errors
Logical errors
This is a human error. A programming mistake that makes a program code to output results.
Syntax error
These are errors that violate rules and regulations or the syntax of a language.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
23
Runtime error
These are the undiscovered error in a program.
Ways to minimize errors
Design your application carefully. More design time means less debugging time.
Use comments where applicable to help you remember what you were trying to do.
Use consistent and meaningful naming conventions for your variables, objects, and procedures.
Run-Time Error Trapping and Handling
Error Handling enables programmers to write clearer, more robust, more fault-tolerant programs. Error handling enables the programmer to attempt to recover (i.e., continue executing) from infrequent fatal errors rather than letting them occur and suffering the consequences (such as loss of application data).
Error handling is designed for dealing with synchronous errors such as an attempt to divide by 0 (that occurs as the program executes the divide instruction). Other common examples of synchronous errors are memory exhaustion, an out-of-bound array index, and arithmetic overflow. Error handling provides the programmer with a disciplined set of capabilities for dealing with these types of errors.
Error-handling code is interspersed throughout a program's code. Errors are dealt with the places in the code where errors are likely to occur. The advantage of this approach is that a programmer reading the code can see the error handling in the immediate vicinity of the code and determine if the proper error handling has been implemented.
Run-time errors are trappable. That is, Visual Basic recognizes an error has occurred and enables you to trap it and take corrective action. If an error occurs and is not trapped, your program will usually end in a rather unceremonious manner. Error trapping is enabled with the On Error statement:
On Error GoTo errlabel
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
24
This uses the GoTo statement. Any time a run-time error occurs following this line, program control is transferred to the line labeled errlabel. Recall a labeled line is simply a line with the label followed by a colon (:).
The best way to explain how to use error trapping is to look at an outline of an example procedure with error trapping.
Private Sub Example ()
Declare variables……………………..
On Error GoTo HandleErrors
Procedure code
Exit Sub
HandleErrors
Error handling code
End Sub
Once you have set up the variable declarations, constant definitions, and any other procedure preliminaries, the On Error statement is executed to enable error trapping. Your normal procedure code follows this statement. The error handling code goes at the end of the procedure, following the HandleErrors statement label. This is the code that is executed if an error is encountered anywhere in the Sub procedure. Note you must exit (with Exit Sub) from the code before reaching the HandleErrors line to avoid execution of the error handling code.
Since the error handling code is in the same procedure where an error occurs, all variables in that procedure are available for possible corrective action. If at some time in your procedure, you want to turn off error trapping that is done with the following statement:
On Error GoTo 0
Once a run-time error occurs, we would like to know what the error is and attempt to fix it. This is done in the error handling code.
Visual Basic offers help in identifying run-time errors. The Err object returns, in its Number property (Err.Number), the number associated with the current error condition. (The Err function has other useful properties that we won’t cover here - consult on-line help for further information.) The Error() function takes this error number as its argument and returns a string description of the
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
25
error. Consult on-line help for Visual Basic run-time error numbers and their descriptions.
Once an error has been trapped and some action taken, control must be returned to your application. That control is returned via the Resume statement. There are three options:
Resume lets you retry the operation that caused the error. That is, control is returned to the line where the error occurred. This could be dangerous in that, if the error has not been corrected (via code or by the user), an infinite loop between the error handler and the procedure code may result.
Resume Next Program control is returned to the line immediately following the line where the error occurred. Resume label Program control is returned to the line labeled label.
When executing the error handling portion of the code and the end of the procedure is encountered before a Resume, an error occurs. Likewise, if a Resume is encountered outside of the error handling portion of the code, an error occurs.
Debugging Visual Basic ProgramsThese are errors that don’t prevent an application from running, but cause incorrect or unexpected results. Visual Basic provides an excellent set of debugging tools to aid in this search. There are no prescribed processes that you can follow to eliminate all logic errors in your program. The usual approach is to eliminate them as they are discovered.
The Immediate Window. The Locals Window.
The Watch Window.
These windows can be accessed from the View menu (the Immediate Window can be accessed by pressing Ctrl+G). Or, they can be selected from the Debug Toolbar (accessed using the Toolbars option under the View menu):
All debugging using the debug windows is done when your application is in break mode. You can enter break mode by setting breakpoints, pressing Ctrl+Break, or the program will go into break mode if it encounters an untrapped error or a Stop statement.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
26
Once in break mode, the debug windows and other tools can be used to:
Determine values of variables Set breakpoints
Set watch variables and expressions
Manually control the application
Determine which procedures have been called
Change the values of variables and properties
Debugging
Unlike other examples, we’ll do this one as a group. It will be used to demonstrate use of the debugging tools.
The example simply has a form with a single command button. The button is used to execute some code. We won’t be real careful about proper naming conventions and such in this example.
The code attached to this button’s Click event is a simple loop that evaluates a function at several values.
Private Sub Command1_Click()
Dim X As Integer, Y As Integer
X = 0
DoY = Fcn(X)
X = X + 1
Loop While X <= 20
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
27
End Sub
This code begins with an X value of 0 and computes the Y value using the general integer function Fcn. It then increments X by 1 and repeats the Loop. It continues looping While X is less than or equal to 20. The function Fcn is computed using:
Function Fcn(X As Integer) As Integer
Fcn = CInt(0.1 * X ^ 2)
End Function
This code doesn’t do much, especially without any output, but it makes a good example for looking at debugger use. Set up the application and get ready to try debugging.
Using the Debugging Tools• There are several debugging tools available for use in Visual Basic. Access to these tools is provided with both menu options and buttons on the Debug toolbar. These tools include breakpoints, watch points, calls, step into, step over, and step out.
The simplest tool is the use of direct prints to the immediate window.
Printing to the Immediate Window:
You can print directly to the immediate window while an application is running. Sometimes, this is all the debugging you may need. A few carefully placed print statements can sometimes clear up all logic errors, especially in small applications.
To print to the immediate window, use the Print method:
Debug.Print [List of variables separated by commas or semi-colons] Debug.Print Example:
Place the following statement in the Command1_Click procedure after the line calling the general procedure Fcn:
Debug.Print X; Y and run the application.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
28
Examine the immediate window. Note how, at each iteration of the loop, the program prints the value of X and Y. You could use this information to make sure X is incrementing correctly and that Y values look acceptable.
Remove the Debug.Print statement.
Breakpoints:
In the above examples, the program ran to completion before we could look at the debug window. In many applications, we want to stop the application while it is running, examine variables and then continue running. This can be done with breakpoints.
A breakpoint is a line in the code where you want to stop (temporarily) the execution of the program that is force the program into break mode. To set a breakpoint, put the cursor in the line of code you want to break on. Then, press <F9> or click the Breakpoint button on the toolbar or select Toggle Breakpoint from the Debug menu. The line will be highlighted.
When you run your program, Visual Basic will stop when it reaches lines with breakpoints and allow you to use the immediate window to check variables and expressions. To continue program operation after a breakpoint, press <F5>, click the Run button on the toolbar, or choose Start from the Run menu.
You can also change variable values using the immediate window. Simply type a valid Basic expression. This can sometimes be dangerous, though, as it may change program operation completely.
Breakpoint Example:
Set a breakpoint on the X = X + 1 line in the sample program. Run the program.
When the program stops, display the immediate window and type the following line:
Print X;Y
The values of these two variables will appear in the debug window. You can use a question mark (?) as shorthand for the command Print, if you’d like. Restart the application. Print the new variable values.
Try other breakpoints if you have time. Once done, all breakpoints can be cleared by Ctrl+Shift+<F9> or by choosing Clear All Breakpoints from
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
29
the Debug menu. Individual breakpoints can be toggled using <F9> or the Breakpoint button on the toolbar.
Viewing Variables in the Locals Window:
The locals window shows the value of any variables within the scope of the current procedure. As execution switches from procedure to procedure, the contents of this window changes to reflect only the variables applicable to the current procedure. Repeat the above example and notice the values of X and Y also appear in the locals window.
Watch Expressions:
The Add Watch option on the Debug menu allows you to establish watch expressions for your application. Watch expressions can be variable values or logical expressions you want to view or test. Values of watch expressions are displayed in the watch window.
In break mode, you can use the Quick Watch button on the toolbar to add watch expressions you need. Simply put the cursor on the variable or expression you want to add to the watch list and click the Quick Watch button.
Watch expressions can be edited using the Edit Watch option on the Debug menu.
Watch Expression Example:
Set a breakpoint at the X = X + 1 line in the example. Set a watch expression for the variable X. Run the application. Notice X
appears in the watch window. Every time you re-start the application, the value of X changes.
At some point in the debug procedure, add a quick watch on Y. Notice it is now in the watch window.
Clear the breakpoint. Add a watch on the expression: X = Y. Set Watch Type to ‘Break When Value Is True.’ Run the application. Notice it goes
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
30
into break mode and displays the watch window whenever X = Y. Delete this last watch expression.
Call Stack:
Selecting the Call Stack button from the toolbar (or pressing Ctrl+L or selecting Call Stack from the View menu) will display all active procedures, that is those that have not been exited.
Call Stack helps you unravel situations with nested procedure calls to give you some idea of where you are in the application.
Call Stack Example:
Set a breakpoint on the Fcn = Cint() line in the general function procedure. Run the application. It will break at this line.
Press the Call Stack button. It will indicate you are currently in the Fcn procedure which was called from the Command1_Click procedure. Clear the breakpoint.
Single Stepping (Step Into):
While at a breakpoint, you may execute your program one line at a time by pressing <F8>, choosing the Step Into option in the Debug menu, or by clicking the Step Into button on the toolbar.
This process is single stepping. It allows you to watch how variables change (in the locals window) or how your form changes, one step at a time.
You may step through several lines at a time by using Run To Cursor option. With this option, click on a line below your current point of execution. Then press Ctrl+<F8> (or choose Run To Cursor in the Debug menu). the program will run through every line up to the cursor location, then stop.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
31
Step into Example:
Set a breakpoint on the Do line in the example. Run the application. When the program breaks, use the Step Into button to single step
through the program.
At some point, put the cursor on the Loop While line. Try the Run To Cursor option (press Ctrl+<F8>).
Procedure Stepping (Step Over):
While single stepping your program, if you come to a procedure call you know functions properly, you can perform procedure stepping. This simply executes the entire procedure at once, rather than one step at a time.
To move through a procedure in this manner, press Shift+<F8>, choose Step Over from the Debug menu, or press the Step Over button on the toolbar.
Step over Example:
Run the previous example. Single step through it a couple of times. One time through, when you are at the line calling the Fcn function,
press the Step over button. Notice how the program did not single step through the function as it did previously.
Function Exit (Step Out):
While stepping through your program, if you wish to complete the execution of a function you are in, without stepping through it line-by-line, choose the Step Out option. The function will be completed and you will be returned to the procedure accessing that function.
To perform this step out, press Ctrl+Shift+<F8>, choose Step Out from the Debug menu, or press the Step Out button on the toolbar. Try this on the previous example.
CLASSES OF DATA TYPES
Numeric data types
These are those data types that will store numbers or numeric values. They are computed mathematically.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
32
Integers – store numbers. Byte – true or false values between 0 and 255.
Real (double) – store 8 bytes of numeric data.
Currency – stores monetary values.
Date and time – store and time format.
Single – store 4 bytes of numeric data.
Long – stores 4 bytes of numeric data.
Decimal – stores 12 bytes of numeric data.
Character data types
They are data types that stores characters or strings of characters.
String – fixed length. Stores 1 to 65,400 characters. String – variable length. Stores 0 to 2 billion characters.
Date – January 1,100 to December 9999
Boolean – stores true or false values.
Object – stores any embedded object.
Variant – numeric. Any value as large as double.
Variant – text. Same as variable length.
Boolean data types
Stores Boolean data types. Boolean is represented by either the keyword true or false or non-zero or zero value. Boolean are stored in two bytes and have no type declaration character.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
33
User defined data types
Visual basic lets the user create his own data type. This is done when you work with mixed data types.
Creating user defined data types
When creating user defined data types use the key word “Type” statement in declaration section of the form. Declare variables associated with the new data types.
Example 1
Private type employee
Name as string
Dateofbirth as date
Hiredate as date
Salary as currency
Gender as string
End type
THE VISUAL BASIC CONTROL STRUCTURESA control structure regulates the flow of a visual basic program, given a condition. Determine the output depending on the conditions used in the
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
34
program. It performs an indicated action only when the condition is false or true.
Types of control structures There are three main control structures in visual basic:
SelectionThey are those control structures that provides options choose from depending on the conditions given for example If, if/then else, switch, and select case.
Iteration These are control structures that repeat statements until a given condition turns true of false for example while/wend, do/until, do/loop while, for/next, do/loop until.
Sequence A control structure that executes statements in a program procedurally; one after another.
If/then selection control structureThis is a control structure that is used to choose among alternative action to take.
Example 1
Determining the age of students in a class.
Interface
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
35
Enter the age
Message
Display the age
Pseudo code/Algorithms Declare the variables i.e. age and messageInitialize variable ageIf age is greater than or equal to 18 thenDisplay “you are a grown up. Learn to be responsible.”End if
Code Private sub cmddisplay_click()Dim age as integerDim message as stringAge=value(txtage.text)If txtage.text>=18 thenTxtmessage.text=”You are a grown up. Learn to be responsible”End ifEnd sub
Flowchart
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
36
Start
If age>=18
Display the message
Stop
The above flowchart represents if/then selection control structure. It illustrates a single selection control structure. It performs the indicated action only if the condition is true otherwise it is aborted.
If/then/else selection control structureThe if/then/else control structure allows a programmer to specify that a different action can be performed when the condition is true. It tsts for true statements in a program.
Example 1A student sat for a DIT II exam an d score the below marks;
SAD= 70 PI= 60 PII= 80 Maths= 40
Required:Create a visual basic program that calculates the average mark. Use the average mark and assign the student the grade according to the grading system below
Key to grading system:A = 80 to 100B =70 to 79C =60 to 69D =50 to 59E =40 to 49F =0 to 39
Interface
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
37
Sad
PI
PII
Maths
Average
Grade
Calculate
Pseudo code/algorithms
Declare variablesInitialize the variable that we inputCalculate the averageIf average is greater than or equal to 80 thenDisplay “A” Else if average is greater than or equal to 70 then Display “B” Else if average is greater than or equal to 60 then Display “C” Else if average is greater than or equal to 50 then Display “D” Else if average is greater than or equal to 40 then Display “E”Else if average is less than 40 then Display “F”
Code Private sub cmdcalculate_click ()Dim SAD, PI, PII, maths as integerDim average as singleDim grade as string SAD=val(txtsad.text)PI=val(txtpi.text)PII=val(txtpii.text)maths=val(txtmaths.text)txtaverage.text= val(txtsad.text)+ val(txtpi.text)+ val(txtpii.text)+ val(txtmaths.text)/4if txtaverage.text>=80 thentxtgrade.text=”A”Else if txtaverage.text>=70 thenTxtgrade.text=”B”Else if txtaverage.text>=60 thenTxtgrade.text=”C”Else if txtaverage.text>=50 then
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
38
Txtgrade.text=”D”Else if txtaverage.text>=40 thenTxtgrade.text=”E”Else if txtaverage.text<40 thenTxtgrade.text=”F”End ifEnd sub
Flow chart
Switch selection control structure
This ia s control structure that is related to if/then/else control structure. Each argument passed to switch control structure is either a condition or a value. If a condition is true the value associated with the condition is returned.
Example 1A student sat for a DIT II exam an d score the below marks;
SAD= 70 PI= 60 PII= 80 Maths= 40
Required:Create a visual basic program that calculates the average mark. Use the average mark and assign the student the grade according to the grading system below
Key to grading system:A = 80 to 100B =70 to 79C =60 to 69D =50 to 59E =40 to 49F =0 to 39Interface
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
39
Sad
PI
PII
Maths
Average
Grade
Calculate
Code Private sub cmdcalculate_click ()Dim SAD, PI, PII, maths as integerDim average as singleDim grade as string SAD=val(txtsad.text)PI=val(txtpi.text)PII=val(txtpii.text)maths=val(txtmaths.text)txtaverage.text= val(txtsad.text)+ val(txtpi.text)+ val(txtpii.text)+ val(txtmaths.text)/4txtgrade.text=switch(txtaverage.text>=80,”A” txtaverage.text>=70,”B” txtaverage.text>=60,”C” txtaverage.text>=50,”D” txtaverage.text>=40,”E” txtaverage.text<40,”E”)End sub
Select case selection control structureThis is a control structure that allows programmers to enter multiple information in a program. It can be used with multiple conditional statements.
Format Select case (expression)Case value 1Block of statements Case value 2Block of statements “ “ ‘Case elseBlock of statements End select
Example 1Determining the grade of an exam in a class.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
40
Marks Marks
Grade
Display
Pseudo-code Declare the variable marks and gradeInitialize the variables marks and grade Select case marks Case is 80 to 100Display “Distinction”Case is 70 to 79Display “Credit”Case is 60 to 69Display “Pass”Case is 50 to 59Display “Referred”Case is 40 to 49Display “Fail”Case elseDisplay “Repeat the course”End select
Code Private sub cmddisplay_click()Dim marks as integerDim grade as stringMarks=val(txtgrade.text)Select case txtmarks.textCase is 80 to 100Txtgrade.text=”Distinction”Case is 70 to 79Txtgrade.text=”Credit”Case is 60 to 69Txtgrade.text=”Pass”
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
41
Case is 50 to 59Txtgrade.text=”Referred”Case is 40 to 49Txtgrade.text=”Fail”Case is 8 to 39Txtgrade.text=”Repeat”End selectEnd sub
Note: the data type specified in the expression must match that of case values.
Flow chart
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
42
Start
Case A
Case B
Case B
Case A action
Case B action
Case Z action
Stop
Iterative control structure
While/wend repetition control structureThis is a repetition control structure that allows programmer to specify that an action is to be repeated based on a true or false condition. The condition given may be true or false. If the condition is false the action stops being executed, but if the condition is true the statements will be repeated until the condition turns false.
Example 1Printing numbers from 1 to 1000
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
43
Display
Code Private sub cmddisplay_click ()Dim x as integerX=2While x<=1000Print xX=x*2WendEnd sub
Do until/loop repetition control structureThe Do until loop repetition control structure repeats until a condition turns false. The statements in the body of a loop are repeatedly executed as long as the loop continuation evaluates to false.
Example 1Printing numbers between 1 and 10
Code Private sub cmddisplay_click()
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
44
Display
Dim x as integerX=1Do until x<=10Print xX=x+1LoopEnd sub
False
True
The For/next repetition control structure It handles the details of counter controlled repetition. When a program starts executing counter variable is initialized to a certain value. The condition is tested by visual basic.
The keywords to is used specify the range of values to be printed. The keyword step is also used to specify the increment operator (value). That is how much will be added to variable counter each time the for/next body executes.
If the keywords Step and to are omitted, the increment value defaults to 1. Always initialize the control variable to certain value.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
45
Start
x<=10 x=x+1
Stop
Example 1Printing numbers between 1 and 10
Code Private sub cmddisplay_click()Dim x as integerFor x=1 to 100 step 2Print xNext xEnd sub
Components of typical for/next loop
Example
For x= 2 to 10 step 2 For= keyword in visual basic x= control variable name 2= initial value To=keyword to specify the range 10=final value for the control variable
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
46
Display
Step= keyword to specify the increment value 2=increment value in control variable
Examples using for/next loop Varying the variable control between 1 and 100
For a=1 to 100 step 1 Varying the variable control from 100 and 1
For b=100 to 1 step -1 Varying the variable control between 7 and 77
For c=7 to 77 step 7 Varying the variable control in the following sequence
99,88,77,66,55,44,33,22,11and 0For d= 99 to 0 step 11
Example 1Calculating the sum of numbers between 1 and 10 using for/next loop
Code Private sub cmddisplay_click ()Dim x as integerX=1Sum=0For x=1 to 1Print xSum=sum+xNext xEnd sub
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
47
Display
Do/loop while repetition control structure This is similar to do while/loop control structure. The condition is tested at the beginning of the loop before the body of the loop is performed.
Do/loop while control structure tests the condition after the loop body is performed. When the loop terminates, execution continues with the statement after the loop while clause.
Flow chart
True
False
Example 1
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
48
Start
Action
x<=10
Stop
Display
Code Private sub cmdprint_click()Dim x as integerX=1DoPrint xX=x+1Loop while x<=10End sub
Do/loop until repetition control structureThis is similar to do until/loop control structure. In do until/loop continuation the condition is tested at the beginning of the loop. In do/loop until the body of the loop is performed first before the condition is tested.
Flow chart
False
True
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
49
Start
Action
x<=10
Stop
Interface
Code Private sub cmdprint_click()Dim x as integerX=1DoPrint xX=x+1Loop until x<=10End sub
Exiting Do and For statements The exit Do and For statements alter the flow of the control structure. The exit Do when used in do/until loop, do/while loop, do loop/while and do until/loop loops causes an immediate exit from the control structure.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
50
Display
Example 1
Code Private sub cmdprint_click()Dim x as integerX=1DoIf x=50 thenExit doEnd ifPrint xX=x+1Loop until x>=100End sub
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
51
Display
Sub-programsRefers to any set of statements forming part of the program used to perform a specific action. The are procedures, modules or parts within the program that are used to carry out a specific task before passing control to the main program.
A properly constructed subprogram should be self contained perform defined operation on a well defined data and have an internal structure independent of the program in which it’s contained.
Types of sub-programs in visual basic
Functions Procedures
A function is any normal procedure but it is used to accept certain inputs and pass them to main program to finish execution. It is used to pass or return a value which will be used to do a certain operation. There are two types of function in visual basic:
Built-in functions User defined functions
Built–in functions Msgbox() functions
The objective of the Msgbox function is to produce a pop-up message box and prompts the user to enter or click on a command button before he/she can continue.
FormatMessage=Msgbox (prompt, stylevalue, title)
Prompt – will display the message in a message box.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
52
Style value – determine the type of command button will appear on the message box.
Example Message=Msgbox(“click to proceed”1,”gretings”)
Style values in Msgbox function
Style Value NAMED CONSTANT BUTTON DISPLAYEED
0 VbOk Ok only
1 VbOkCancel Ok and Cancel
2VbAbortRetryIgnore
Abort, Retry and Ignore
3 VbYesNoCancel Yes, No, Cancel
4 VbYesNo Yes, No
5 Vbretycancel Retry, Cancel
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
53
Example 1
Code Private sub cmdcalculate_click ()Dim SAD, PI, PII, maths as integerDim average as singleDim grade as string Dim message as stringSAD=val(txtsad.text)PI=val(txtpi.text)PII=val(txtpii.text)maths=val(txtmaths.text)txtaverage.text= val(txtsad.text)+ val(txtpi.text)+ val(txtpii.text)+ val(txtmaths.text)/4if txtaverage.text>=80 thenmessage=Msgbox(“DISTINCTION”,2,”Startup Menu”)Else if txtaverage.text>=70 thenmessage=Msgbox(“CREDIT”,2,”Startup Menu”)Else if txtaverage.text>=60 thenmessage=Msgbox(“PASS”,2,”Startup Menu”)Else if txtaverage.text>=50 thenmessage=Msgbox(“REFERRED”,2,”Startup Menu”)Else if txtaverage.text>=40 thenmessage=Msgbox(“DISTINCTION”,2,”Startup Menu”)Else if txtaverage.text<40 thenmessage=Msgbox(“REPEAT”,2,”Startup Menu”)End ifEnd sub
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
54
Sad
PI
PII
Maths
Average
Grade
Calculate
Icons Displayed In Msgbox () Function
Style Value
Text DisplayedIcon
16 Stop sign
32 Question mark
48Exclamation point
64 Information icon
Input box functionThe input box function is used to display a message box whwre the user can enter a value or message in form of text.
FormatMessage=inputbox (prompt, title, default text, x-position, y-position)
Prompt – the message normally displayed as a question.Title – the title of the inputbox function.Default text – a text that appears in the inputbox field where the users can use it as his or her intended input or information he wishes to key in.X and y position – indicate the coordinates of inputbox.
Example 1
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
55
Total
Add
Private sub cmdadd_click()Dim total as integerDim x, y as integerX=inputbox (“enter the value of x”)Y=inputbox (“enter the value of y”)Txttotal.text=x+yEnd sub
User defined functionsThese are those functions that user/programmer creates to perform a certain operation.
Format Public function functionname (arg as datatype………….) as datatypePrivate function functionname (arg as datatype………..) as datatype
Public indicates that the function is applicable is to the whole program and private indicates that the function applicable to certain modules, statement or procedures only. User defined function can be created with add procedure dialog box. They can also be created in the code window by typing directly into it
Example 1Write a visual basic function using a function to calculate the grade of student based on average mark.
Interface
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
56
Visual basic codePublic Function grade(marks As Variant) As VariantSelect Case txtmark.TextCase 80 To 100txtgrade.Text = "DISTINCTION"Case 70 To 79txtgrade.Text = "CREDIT"Case 60 To 69txtgrade.Text = "PASS"Case 50 To 59txtgrade.Text = "REFFERED"Case 40 To 49txtgrade.Text = "FAIL"Case 0 To 39txtgrade.Text = "REPEAT"End SelectEnd FunctionPrivate Sub cmddisplay_Click()Dim remarks As VariantDim mark As Variantmark = Val(txtmark.Text)remarks = grade(marks)End Sub
Example 2Using a visual basic function calculate the area of a circle given:Pi=3.142Radius=14cm
Solution
Visual basic CodePublic Function area(r As Variant) As VariantConst pi = 3.142Area = pi * r * rEnd Function
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
57
Private Sub cmdcompute_Click ( )Dim radius As VariantRadius = Val (txtradius.Text)Dim areas As VariantAreas = area (radius)MsgBox ("The area is:" & areas)End Sub
Example 3Write a visual basic function that will calculate and display interest in textbox given:
Amount =Kshs.10, 000Interest rate = 10%Period = 2 years
Solution
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
58
Visual basic codePublic Function interest (p As Variant, r As Variant, y As Variant) As VariantInterest = p * r * y / 100End Function
Private Sub cmdcalculate_Click()Dim amount As VariantDim principle As Variant
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
59
Dim rate As VariantDim years As VariantPrinciple = Val(txtprinciple.Text)Rate = Val(txtrate.Text)Years = Val(txtyears.Text)Amount = interest(principle, rate, years)MsgBox ("The Future Value is: " & amount)End Sub
Assignment to the students
Using a function write a program that prints numbers from 10 to 0 but when it goes below zero it exits from executing.
Write a visual basic program that accepts any three integers and then determines the highest number among them. Use a function.
Write a visual basic program that accepts any three integers. Let the program divide the integers by numbers of integers entered. If it attempts to divide by zero exit the execution.
Procedures A procedure is a predefined function used to solve a problem in a project.
Types of procedures in visual basic Event procedures
These are procedures used to design programs that respond to events. For example
Private Sub cmdcompute_Click()Block of statementsEnd Sub
General proceduresThese are procedures that are used to access any statement in a program. For example
Const pi=3.142Rate=10%
Sub procedures These are sub-routines which are logically accessed by programs in projects. They are local to the main program for example:
Private Sub cmdcompute_Click ()Block of statementsEnd Sub
Private sub calculate (arguments)
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
60
Block of statements End sub
Function proceduresA function returns a value to the calling function or statements for example:
Private Function area (length as integer, width as integer) as integerBlock of statements End Function
Function and procedure callingA function or procedure is called tom perform a certain operation. It then returns a value to the calling (main program) function statement or procedure.
A function return value is specified in the body of the program by assigning a value to the function procedure name. Control then returns to the calling statement.
Call-by-referenceWith call-by-reference the caller gives the called procedure or function the ability to directly access data and modify data if he called procedure of function so wishes.Call-by-valueWhen an argument is called by value a copy of the of arguments’ value is passed to the calling procedure. Arguments passed by value use keyword Byval or by enclosing the arguments in parenthesis (). The arguments passed by references use the keyword Byref. For example:
Function interest (Byval x as integer as integer) as integerFunction interest (Byref x as integer as integer) as integer Parameter passingParameters are those variables that are used to hold data to be passed to the calling statement or procedure. The process of transferring these parameters is called parameter passing. Arguments are real or actual values passed to calling statement or procedure.
Types of parameters
Formal parametersThese are labeled memory blank areas that are to be used to store values to be used during execution. They are identifiers rather than reserved words.
Actual parameters
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
61
These are variables that replace the formal parameters when the procedure or function is called. They are given the actual parameter list of procedure call.
Classes of parameters
Value parametersUsed to supply information to the procedure but they cannot be used to get information out of a procedure. Value parameters are declared by including their names and the corresponding datatype within a procedure header.
Variable parameterUsed in applications where information must be transferred in both directions between the procedure and procedure reference. When the procedure containing a variable parameter is accessed the actual parameter in the procedure reference is substituted by the formal parameter within the procedure itself.
Recursive Functions
A recursive function/procedure calls itself either directly or indirectly through another call. Functions call other functions or procedures to return values. It is equally possible for a function to call itself.
A recursive function or procedure is called to solve a certain problem. A recursive function or procedure problem solving approaches have a number of elements in common. The procedure only knows how to solve the simplest case(s) so called base case(s). If called with base case, the procedure stops recursively calling itself and simply returns to its caller.
If called with a more complex problem, the procedure divides the problem into two conceptual pieces; a piece that knows what to do and a piece that doesn’t know how to do it. The latter piece must resemble the original problem, but with a slightly simpler or smaller version of original problem. Because this new problem looks like the original the procedure launches a fresh copy (a call) of itself to go to and work on smaller problem. THIS IS CALLED RECURSIVE CALL.
Example 1 Demonstrating factorial function
Factorials are written using the! Symbol, and are defined as follows:
0!=1(by definition) 1!=1 2!=2x1=2 3!=3x2x1=6
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
62
4!=4x3x2x1=24 5! = 5 x 4 x 3 x 2 x 1 = 120
To get factorial quickly we multiply the number by the previous factorial, i.e. 5! = 5 x 4! Similarly, 9! = 9 x 8! And 103! = 103 x 102! This means that if you know a factorial you can easily get the next one in the series.
Visual basic code
Public Function factorial(ByVal y As Double) As DoubleIf y <= 1 Thenfactorial = 1 'Base caseElsefactorial = y * factorial(y - 1) 'Recursive callEnd IfEnd Function
Private Sub cmdcalculate_Click()Dim x, n As IntegerCall lstvalues.Clearn = txtinput.Text
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
63
For x = 0 To nlstvalues.AddItem Format$(x, "@@") & "!=" & -factorial((x))Next xEnd Sub
Recursion and iterationBoth recursion and iteration are based on control structure. Iteration uses repetition control structure while recursion uses selection control structure.
Both recursion and iteration involve recursion. Iteration explicitly uses repletion control structure while recursion achieves repetition through repeated procedure calls.
Iteration and recursion each involve termination test. Iteration terminates when the loop continuation condition fails, while recursion terminates when the base case is recognized.
Iteration keeps modifying a counter until the counter assumes a value that makes loop continuation condition fail, recursion keeps producing smaller or simpler version of the original problem until the base case is reached.
Both iteration and recursion can occur infinitely. An infinite loop loop occurs with iteration if loop continuation test becomes false, infinite recursion occurs if the recursion step (call) does not reduce the problem each time in a manner that converges on a base case.
Scope of variablesThe scope of variables refers to the coverage or extent of variable reference in a program. In visual basic there are three scopes of variable:
Local scopeThese are variables declared in a procedure’s body. Local variables are only referenced from where they are declared through end sub or end function.
Module scopeThese are variables declared in general declaration with dim keyword. By default, module variables can only be referenced in module in which they are declared. They are sometimes declared private scope.
Public scopeRefers to variables that are declared public. They are accessible to all modules.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
64
Data structures These are variable that are used hold data that contain two or more elements together instead of single element. A tool for handling logically related data items. They are user defined and provide a method for packing together of different types and structure.
Classes/types of data itemsThere are two types of data structure:
Static fixed-size data structureThey are data structures that don’t change during program execution.
Dynamic data structure They are data structure that changes when the program executes.
Data structures types
Arrays This is a consecutive group memory of locations that all have the same name and datatype. This is a list of variables all with the same name and data type. When we work with single item, we only we only need to use one variable. However, if we have a list of item which are similar in type we need to declare an array of variables instead of using a variable for each item. For example:
Format Dim|Public|Private ArrayName(Subscript) As DataType
ArrayName is the name of the array. Subscript is the dimensions of the array. DataType is any valid data type.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
65
Dim name as integer ‘single itemDim names (10) as string ‘more than two item
To refer to a particular location or element in the array, we specify the array name and an array element position number. For example:
Dim numbers (3) as integer
Fixed-size array
Dim array1 (6) As String
Private Sub Form_Load()array1(0) = "Kisii"array1(1) = "Kisumu"array1(2) = 1234array13) = 342array1(4) = 234array1(5) = 9804End Sub
Dynamic array Redim preserve array1 (0 to 7) As String
Private Sub Form_Load()array1(0) = "Kisii"array1(1) = "Kisumu"array1(2) = 1234array13) = 342array1(4) = 234array1(5) = 9804Array1(6)=675End Sub
Declaring arrays
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
66
Arrays can be declared as public in the code module, local. Module array are declared at general declarations using dim or private keywords. Local arrays are declared I the procedure using thew keywords dim or static. For example: Dim names (10) as string
Public declared arrays declare arrays that are used throughout the program or application. The dim declaration arrays declare arrays that are only used in the procedure. The name of the arrays states the name to be used to be used to store arrays. The value or position number defines the upper bound (highest value) of the numbers and the lower bound(lowest value is zero(0).
Vb 1 dimensional array (1D)
Name(1)Name(2)
Name(3)
Name(4)Name(5)
Name(6)
Name(7)
Name(8)
Name(9)
Name(10)
This is an array that consists of rows only.
Example 1Use an array and print ten names on a form.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
67
Dim studentName(10) As StringDim num As IntegerPrivate Sub cmdprint_Click()For num = 1 To 10studentName(num) = InputBox("Enter the student name", "Student names", "", 1500, 4500)If studentName(num) <> "" ThenForm1.Print studentName(num)ElseEndEnd If
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
68
NextEnd Sub
Example 2Use an array and print ten names on a list box.
Code Dim studentName(10) As StringDim num As IntegerPrivate Sub addName()For num = 1 To 10studentName(num) = InputBox("Enter the student name")List1.AddItem studentName(num)NextEnd Sub
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
69
Private Sub cmdprint_Click()addNameEnd Sub
Example 3
Use an array to print random numbers from 1 to 100 on a form.
Code
Dim numbers(10) As IntegerPrivate Sub cmdprint_Click()Dim x As IntegerRandomizeFor x = 1 To 10numbers(x) = Int(20 * Rnd + 2)
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
70
Next xFor x = 1 To 10Print numbers(x)Next xEnd Sub
Multidimensional arrays
These are those arrays that contain two or more indexes. Arrays that require two or more indexes to identify. For example:
Dim a (2, 2) as integerDim x (2, 4) as integer
Like one dimensional array, multidimensional arrays can have public and local module scope. Function Lbound and Ubound can also used with multidimensional arrays. When calling the Ubound and Lbound the dimension is passed as an argument.
Example 1
Write a visual basic that produces the data shown below on a form.
Sales for May 2010
Week Sun Mon Tue Wed Thur Fri1 300 200 400 90 240 7002 345 120 504 100 300 5003 500 530 560 300 565 6004 440 452 432 323 300 500
Solution
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
71
Dim sales(5, 6) As String
Private Sub Form_Load()sales(1, 0) = "WEEK"sales(1, 1) = "SUN"sales(1, 2) = "MON"sales(1, 3) = "TUE"sales(1, 4) = "WED"sales(1, 5) = "THUR"sales(1, 6) = "FRI"
sales(2, 0) = 1sales(2, 1) = 300sales(2, 2) = 200sales(2, 3) = 400sales(2, 4) = 90sales(2, 5) = 240sales(2, 6) = 700
sales(3, 0) = 2
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
72
sales(3, 1) = 345sales(3, 2) = 120sales(3, 3) = 504sales(3, 4) = 100sales(3, 5) = 300sales(3, 6) = 500
sales(4, 0) = 3sales(4, 1) = 500sales(4, 2) = 530sales(4, 3) = 560sales(4, 4) = 300sales(4, 5) = 565sales(4, 6) = 600
sales(5, 0) = 4sales(5, 1) = 440sales(5, 2) = 452sales(5, 3) = 432sales(5, 4) = 323sales(5, 5) = 300sales(5, 6) = 500End Sub
Private Sub cmddisplay_Click()Print sales(1, 0), sales(1, 1), sales(1, 2), sales(1, 3), sales(1, 4), sales(1, 5), sales(1, 6)Print sales(2, 0), sales(2, 1), sales(2, 2), sales(2, 3), sales(2, 4), sales(2, 5), sales(2, 6)Print sales(3, 0), sales(3, 1), sales(3, 2), sales(3, 3), sales(3, 4), sales(3, 5), sales(3, 6)Print sales(3, 0), sales(3, 1), sales(3, 2), sales(3, 3), sales(3, 4), sales(3, 5), sales(3, 6)Print sales(4, 0), sales(4, 1), sales(4, 2), sales(4, 3), sales(4, 4), sales(4, 5), sales(4, 6)Print sales(5, 0), sales(5, 1), sales(5, 2), sales(5, 3), sales(5, 4), sales(5, 5), sales(5, 6)End Sub
Control arrayControl arrays group together controls that provide same name and functionality. Each control array element maintains its own properties but shares its event procedure code with other control array element. Control arrays can be created in several ways, either by giving a control same name as another or by copying the forms and pasting the copy on a form.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
73
Function arraysThese are arrays that return a variant array at execution time. The values passed to arrays specify element values in returned array. The returned array element Lbound I either 1 or 0 depending on option base.
Searching arrays
There are two techniques to search for arrays: Linear search
The computer compares each element of an array with the search key. Search key I the index specify the way to search for.
Binary search In binary search the algorithm removes from consideration on behalf of the element in the array searched for after each comparison. The algorithm locates the middle element of the array and compares it with search key. If they are equal the search key is found and the array index of that element is returned.
Example 1
Demonstrating linear search
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
74
Vb code Private Sub cmdsearch_Click()Dim searchkey As IntegerDim element As Integerlblresult.Caption = ""searchkey = txtkey.Textelement = linearsearch(array3(), searchkey)If element <> -1 Thenlblresult.Caption = "Value was found"Elselblresult.Caption = "Value was not found"End IfEnd Sub
Private Sub lstdata_click()Dim x As IntegerCall RandomizeCall lstdata.Clearlblresult.Caption = ""For x = LBound(array3) To UBound(array3)
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
75
Does Not Like Cakes
array3(x) = 1 + Int(100 * Rnd())Call lstdata.AddItem(array3(x))Next xEnd SubPublic Function linearsearch(y() As Integer, key As Integer) As IntegerDim x As IntegerFor x = LBound(y) To UBound(y)If y(x) = key Thenlinearsearch = xExit FunctionEnd IfNext xlinearsearch = -1End Function
Private Sub Form_Load()Call lstdata_clickEnd Sub
QUEUES This a chain of of data items in the computer memory awaiting execution. Queues use FIFO, first datum in is the first datum out.
Characteristics of queues Data is entered to the end but removed from the front. The term FIFO is used to describe queues because first datum in is the
first datum out. Each data stays in the storage location until its turn comes thereby
reducing time spent in data movement.Overflow and underflowUnderflow occurs when an attempt is made to remove data from an empty queue. Overflow occurs when an attempt is made to add data to a queue when all available memory space are occupied.
Linked lists Lists are flexible ways of handling data items in order. For example:
Alex
Each word in the sentence is a data item, which is linked to the next data item by a pointer. Datum plus a pointer make a node or element of a list. The last item in the list is a terminator. This may be stored in an array of records. Each
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
76
row of an array is one element in the list. A start pointer saying where the first datum is stored and a free storage pointer saying where the next datum can go.
Start pointer
Free storage pointer
Types of linked lists Single linked lists
The element of the record has only one pointer.
Head
Double linked lists The element of the record has two pointers, one pointer for giving the address of the following record another for giving the address of the proceeding record.
Head
R
Circular linked lists
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
ROW NO DATUM POINT TO THE NEXT NO COMMENT1 “ALEX” 2 NEXT
DATUM2 “DOES” 3 NEXT
DATUM3 “NOT” 4 NEXT
DATUM4 “LIKE” 5 NEXT
DATUM5 “CAKES” -1 LAST
DATUM6 EMPTY7 EMPTY
77
Address 1 Address 2 Address 3
The pointer of the last record gives the address first record thus this form a circular or ring of records.
Trees Trees these are hierarchal data structure constructed using rule of precedence for data items using alphabetical or numerical sequence. The elements of a tree are called nodes and each element consists of a datum and at least two pointers.
56 42 89 65 48
56 is the first datum placed I the tree. Its node is therefore called parent node or root node. We add 42 to the tree next using rule of precedence; lower number to the left and higher number to the right.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
78
Address 1 Address 2 Address 3
Left pointer Datum Right pointer
42
Start
56
89
-1 48 -1
-1 65 -1
STACKS They are used to temporarily store information or data. Related to queues but data is removed and added differently. Data is added at the top and removed from top using LIFO.
Next removal pointerLocation of address 101 102 103 104 105 106 107 108 109 110Contents 20 4 19 12 16Order of arrival 1 2 3 4 5Order of removal 5 4 3 2 1
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
79
AS
BS
ES
KS
D
J
C
E H
QM
F
P
AS
S
FILE INPUT/OUTPUT
A file is a collection of data on a given subject, stored in a storage memory. We have executable files with .EXE extensions, library files with .DLL extensions, word files with .DOC extensions etc.
Terms used in files Record
A logical section of a file that holds related data set. Field
A field is a section of a record which defines specific information. I/O
Stands for input output. This is a means of writing and reading from a file.
Types of files in visual basicAssignment
File organization methods Sequential files
This is a method where the files are written in order from beginning to the end.Advantages
Disadvantages Random files
A file where all records are accessible individually. They are scattered in a storage media.Advantages
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
80
Disadvantages Binary file
The data is stored in byte level and you can read and write individually to the file.
Serial file They are files stored in series of one another.Advantages
Disadvantages Indexed files
These are files that are stored and accessed using indexes. The files are accessed using keys.Advantages
Disadvantages
Opening The OPEN command is used to open files. Open command assigns the files to a numbered file handle, also called channel or sometimes buffer.
Syntax/formatOpen “file number” [accessmode][accessrestriction][locktype]as # filenumber
Example 1 Open “Git.txt” for random read lock read as #1 “Git.txt” is the name of the file i9n the directory. For random means access to the record can be random. Read restricts access of the file to read only. Lock read means that only persons reading the records can have access
to it at any time. As # 1 means that the file is assigned to handle # 1.
Access modes Input
It is open for sequential files input; the file will be read sequentially starting with the beginning.
OutputIt is open for sequential files output; the file will be read sequentially starting with the beginning.
Random
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
81
Open to read and write; any specific record can be accessed. Append
Sequential output to the end of existing files; does not overwrite the file.
Closing files The CLOSE command is used to close all the open files.
Syntax/format
Close #fileformat1 [ #filenumber2]……………………….
Creating a sequential file in visual basic There are two commands that allow reading and writing to a file sequentially.
Print – reading Write – writing
They work almost the same only that print does not separate the fields in the file which makes data harder to read later.
Format Write #filenumber, outputlist.
File number is the number the file was opened with. Output list is one or more variables you want write to the file.
Example 1Create a simple contacts file to store the student’s records (contacts).
File design
Determine the fields to have on the address book for example seven textboxes.
Determine the name of the address book for example “contacts.txt” Determine where to store the file for example “C:\”. We must know the
location for the purpose of the open statement. Determine the mode of access for the file when we output it for example
input, output, random, append etc. Set the tab order; use the tab index property at properties window for
each control on the form. It enables the user to tab as he enters data. For controls that don’t have focus such as labels set their tabstop
property to false.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
82
In setting properties for textboxes we will use control arrays technique. This is where we name one textbox and copy the same name to other six textboxes; txtfield (0) to txtfield (6). This creates an array of textboxes for output form (file).
Vb codePrivate Sub cmdwrite_Click ( )Dim x As IntegerDim y As IntegerFor x = 0 To 6Write #1, txtfield(x).TextNext xFor y = 0 To 6txtfield(y).Text = ""Next yEnd Sub
Private Sub cmdcancel_Click()Dim x As Integer
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
83
For x = 0 To 6txfield(x).Text = ""Next xtxtfield (0).SetFocusEnd SubPrivate Sub cmdexit_Click()Unload Form1End Sub
Private Sub Form_Load()Dim x as IntegerFor x = 0 To 6txtfield(x).Text = ""Next xOpen "C:\contacts.txt" For Append As #1End Sub
Creating a random file in visual basicSince the file format for random file is different from the sequential file we will create a new output file called “phonebook.txt”. We will add a field for Personid at the beginning of each record. This allows the retrieval of records using a record number.
User defined data types We will user defined data types to simplify input-output operations since the Get and Put commands only insert one field at a time. We will create a new variable that contains a whole record. The user defined data types must be declared in the module. Any information declared in the module is available to all forms in the application.
Private type phonerecordPersonalid as integerFname as string * 15Lname as string * 15Address as string * 15Province as string * 10Town as string * 10Code as string * 10Phone as string *10
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
84
End type
The type statement creates a new data called phonerecord. The remaining type can be like any other string or integer. The individual fields in the structured variable can be accessed using dot notation.
Txttown.text=inrecord.town
In random files it is important to determine the length of the string.
Fname as string *15
Writing records to filesThe command used to write records to random files is Put.
Format
Put #filenumber, [recordnumber], variable.
The recordnumber is optionalVariables are written in the next record position after the last put or get statement if omitted.
Reading records from fileThe command to read records from the random file is Get.
Format
Get #filenumber, [filenumber, [recordnumber], variable
If record number is omitted the next record is read from the file.
Creating random fileWe will write a code using the user defined data types called “phonebook” that will obtain the next record number from file, accepts input from user and write the record out of the file.
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
85
Dim outrecord As phonerecordDim inrecord As IntegerDim position As IntegerDim lastrecord As Integer
Private type phonerecordPersonalId As IntegerFname As String * 15Lname As String * 15Address As String * 20Province As String * 15Town As String * 10Code As String * 8Phone As String * 15End type
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
86
Private Sub cmdwrite_Click ( )Dim x As IntegerPosition = position + 1txtfield(0).Text = positionoutrecord.PersonalId = positionoutrecord.Fname = txtfield(1).Textoutrecord.Lname = txtfield(2).Textoutrecord.Address = txtfield(3).Textoutrecord.Town = txtfield(4).Textoutrecord.Province = txtfield(5).Textoutrecord.Code = txtfield(6).Textoutrecord.Phone = txtfield(7).TextPut #1, , outrecordFor x = 0 To 7txtfield(x).Text = " "Next xEnd Sub
Private Sub cmdcancel_Click()Dim x As IntegerFor x = 0 To 4txtfield(x).Text = ""Next xtxtfield(0).SetFocusEnd Sub
Private Sub Form_Load ( )Dim x As IntegerFor x = 0 To 7txtfield(x).Text = ""Next xOpen "C:\contacts.txt" For Random As #1Do While Not EOF (1)Get #1, , outrecordLoopPosition = lastrecordLastrecord = Seek (1) - 1End Sub
VISUAL BASIC AND DATABASES (MS ACCESS 2003/2007 OR MSSQL)
VISUAL BASIC 6.0 TUTORIALPREPARED BY: KABA N. DANIEL
87
Top Related