SlideShare a Scribd company logo
1 of 37
Download to read offline
Unit 3
ERROR CONTROL & FILE
HANDLING
1
R. BHUVANESWARI
ASST.PROFESSOR
DEPT OF COMPUTER SCIENCE AND APPLICATION
DKM COLLEGE FOR WOMEN
(AUTONOMOUS)
VELLORE
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 2
Arrays
 An array is a consecutive group of memory locations that all have
the same name and the same type.
 Arrays are programming constructs that store data and allow us to
access them by numeric index or subscript
 To refer to a particular location or element in the array, we specify
the array name and the array element position number. i.e index
 Arrays helps us create shorter and simpler code in many situations.
 All arrays in VB are zero based, i.e, the index of the first element
is zero and they are numbered sequentially.
 The upper bound is the number that specifies the index of the last
element of the array.
 Arrays are declared using Dim, ReDim, Static, Private, Public and
Protected keywords.
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 3
Array Decleration
 The dimensionality of an array refers to the number of subscripts
used to identify an individual element.
 There are 3 types of array
 1. one dimensional array(one index) e.g -A()
 2. two dimensional array (two index) e.g A()()
 3. multi – dimensional array (more than 2 index)
Declaring arrays
 Arrays occupy space in memory.
 The programmer specifies the array type and the number of
elements required by the array
 arrays are declared in the general declarations using keyword Dim
or Private.
 Arrays may be declared as Public also.
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 4
Static arrays (fixed array)
 There are two types of arrays in Visual Basic namely:
 Fixed-size array(static array) : The size of array always remains
the same-size doesn't change during the program execution.
 Dynamic array : The size of the array can be changed at the run
time- size changes during the program execution
Fixed-sized Arrays(static array)
 When an upper bound is specified in the declaration, a Fixed-array
is created.
 The upper limit should always be within the range of long data type.
Declaring a fixed-array
 Dim numbers(5) As Integer
 The above declaration creates an array with 6 elements, with index
numbers running from 0 to 5.
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 5
Dynamic arrays
dynamic arrays
 when we do not know the size of the array we use dynamic array.
 its number of elements can be changed at run time.
 E.g
 Dim Test() as Integer
 Here the size of the array is not specified
 Dynamic arrays are arrays that can be dimensioned and re-
dimensioned as par the need of the program.
 You can declare a dynamic array using the ReDim statement.
 The Preserve keyword helps to preserve the data in an
existing array, when you resize it.

Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 6
Reinitializing Arrays(ReDim)
 We can change the size of an array after creating them.
 The ReDim statement assigns a completely new array object to the
specified array variable.
 You use ReDim statement to change the number of elements in an
array.
 The following lines of code demonstrate that.
 This code reinitializes the Test array declared above.
'Reinitializing the array
 Dim Test(10) as Integer
 ReDim Test(25) as Integer
 When using the Redim statement all the data contained in the
array is lost.•
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 7
preserve keyword in an array
 If you want to preserve existing data when reinitializing an array then you should
use the Preserve keyword
 which looks like this:
 Dim Test() as Integer={1,3,5}'declares an array an initializes it with three
members
 ReDim Preserve Test(25)'resizes the array and retains the data in elements 0 to 2
E.G program with redim and preserve:
Dim Test() As Integer = {1, 3, 5}
For i = 0 To 2
ListBox1.Items.Add(Test(i))
Next–ReDim Preserve Test(6)
Test(3) = 9
Test(4) = 19
Test(5) = 67
For i = 3 To 5
ListBox1.Items.Add(Test(i))
Next
Finally the list box
consist of 6 items
namely
1,3,5,9,19,67
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 8
Control Arrays
 A control array is a group of controls that share the
same name and the same event procedures.
 he properties of the controls in the control array can vary
 Adding controls with control arrays uses fewer resources
than adding multiple control of same type at design time.
 A control array can be created only at design time.
 You create a control and then assign a numeric, non-negative
value to its Index property;
 Control arrays are one of the most interesting features of
the Visual Basic environment, and they add a lot of
flexibility to your programs:
 this often dramatically reduces the amount of code you
have to write to respond to a user's actions.
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 9
CREATING Control Arrays
 you can dynamically add new elements to a control array at
run time; in other words, you can effectively create new
controls that didn't exist at design time.
 You create two controls of the same class and assign them
an identical Name property. Visual Basic shows a dialog box
warning you that there's already a control with that name
and asks whether you want to create a control array. Click on
the Yes button.
 You select a control on the form, press Ctrl+C to copy it to
the clipboard, and then press Ctrl+V to paste a new instance
of the control, which has the same Name property as the
original one. Visual Basic shows the warning mentioned in the
previous bullet.
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 10
example for control array
• Calculator program is an example
for control array.
• For more information visit:
https://www.freetutes.com/learn-
vb6/lesson11.html
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 11
Procedures in VB
• Visual Basic offers different types of procedures
• It is a small sections of coding in applications
• Visual Basic programs can be broken into smaller logical components called
Procedures.
• It is useful for repeated operations such as the frequently used calculations, text
and control manipulation etc
benefits of using procedures:
1. t is easier to debug a program with procedures, because it breaks a program into
discrete logical limits.
2. Procedures used in one program can act as building blocks for other programs with
slight modifications.
Types of procedures:
VB supports 2 types of procedures. They are:
1. Sub Procedure
2. Function or Property Procedure.
Procedure
Sub Procedure Function Procedure
Event Procedure General Procedure
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 12
• A sub procedure can be placed in standard, class and form modules.
• Whenever the procedure is called, the statements between Sub and End
Sub are executed.
• Header of the sub procedure consist of 3 things
1. scope of the procedure(private/public/static)
2. Name of the procedure
3. Argument list
Syntax:
[Private | Public] [Static] Sub Procedurename [( arglist)]
[ statements]
End Sub
• Here, arglist is a list of argument names separated by commas(if more
than one argument is present).
• Each argument acts like a variable in the procedure
Types of sub procedure:
1. Event Procedures
2. General Procedures
Sub Procedures
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 13
Event Procedure:
 An event procedure is a procedure block that contains the control's actual name,
an underscore(_), and the event name.
 The following syntax represents the event procedure for a Form_Load event.
Private Sub Form_Load()
[statement block]
End Sub
Event Procedures acquire the declarations as Private by default.
General Procedures:
 A general procedure is declared when several event procedures perform the same
actions.
 It is a good programming practice to write common statements in a separate
procedure (general procedure) and then call them in the event procedure.
To add General procedure:
 Select Add Procedure option from the Tools menu, which opens an Add Procedure
dialog box as shown in the figure given below.
Event Procedure
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 14
 In the name of the procedure type the Name in textbox
 Under Type, Sub is selected to create a Sub procedure, Function to create a
Function procedure or Property to create a Property procedure.
 Under Scope, Public is selected to create a procedure that can be invoked outside
the module, or Private to create a procedure that can be invoked only from within
the module.
We can also create a new procedure in the current module by typing Sub
ProcedureName, Function ProcedureName, or Property ProcedureName in the Code
window
General Procedure
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 15
 Functions are same like sub procedures, except they return a value to the calling
procedure.
 They are especially useful for taking one or more pieces of data, called
arguments and performing some tasks with them.
 Then the functions returns a value that indicates the results of the tasks
complete within the function.
 Here Header of the function consist of 3 things
1. Name of the procedure
2. Argument list
3. Return type
Example:
Function Hypotenuse (A As Double, B As Double) As Double
Hypotenuse = sqr (A^2 + B^2)
End Function
Function Procedures
Fun name
Arguments list Return type
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 16
Property Procedures
 property procedure is used to create and manipulate
custom properties.
 It is used to create read only properties for Forms,
Standard modules and Class modules.
 Visual Basic provides three kind of property
procedures
1. Let procedure - that sets the value of a property,
Property
2. Get procedure - that returns the value of a property,
and Property
3. Set procedure - that sets the references to an
object.
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 17
Multiple Forms in Visual Basic
 most Visual Basic applications use multiple forms.
 To add a form to an application, click the New Form button
on the toolbar or select Form under the Insert menu.
 On each form we can draw the controls, assign properties,
and write code.
 You need to decide when and how you want particular forms
to be displayed.
 The user always interacts with the ‘active’ form.
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 18
Multiple Form Example
 Start a new application. Put two command buttons on the form (Form1).
 Set one’s Caption to Display Form2 and the other’s Caption to Display
Form3.
 The form will look like this:
 Attach this code to the two
command buttons Click events.
Private Sub Command1_Click()
Form2.Show vbModeless
End Sub
Private Sub Command2_Click()
Form3.Show vbModal
End Sub
Add a second form to the application (Form2).
Place a command button on the form. Set its Caption to Hide Form
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 19
Multiple Form Example
 Atta ch this code to the button’s Click event.
Private Sub Command1_Click()
Form2.Hide
Form1.Show
End Sub
 Add a third form to the application (Form3).
 This form will be modal. Place a command button on the form.
 Set its Caption to Hide Form
Attach this code to the button’s Click event.
Private Sub Command1_Click()
Form3.Hide
Form1.Show
End Sub
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 20
Multiple Form Example
 Attach this code to the two command buttons Click events.
 Private Sub Command1_Click()
 Form2.Show vbModeless
 End Sub
 Private Sub Command2_Click()
 Form3.Show vbModal
 End Sub
 Make sure Form1 is the startup form (check the Project
Properties window under the Project menu).
 Run the application.
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 21
Do events
 DoEvents passes control to the operating system
 Control is returned after the operating system has finished processing.
 The DoEvents function returns an Integer representing the number of open
forms in stand-alone versions of Visual Basic.
 DoEvents is most useful for simple things like allowing a user to cancel a
process after it has started, for example a search for a file.
 Example
Dim I,
For I = 1 To 150000 ' Start loop.
If I Mod 1000 = 0 Then ' If loop has repeated 1000 times.
OpenForms = DoEvents ' Yield to operating system.
End If Next I
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 22
Sub-main function
 Every Visual Basic application must contain a procedure
called Main.
 This procedure serves as the starting point and overall
control for your application.
 Main contains the code that runs first
 In Main, you can determine which form is to be loaded first
when the program starts.
Declaring the Main Procedure
Sub Main()
MsgBox("The Main procedure is starting the application.")
' Insert call to appropriate starting place in your code.
MsgBox("The application is terminating.")
End Sub
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 23
Sub-main function
Sub-main as a function
Function Main() As Integer
MsgBox("The Main procedure is starting the application.")
Dim returnValue As Integer = 0
MsgBox("The application is terminating with error level " &
CStr(returnValue) & ".")
Return returnValue
End Function
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 24
Error trapping
 No matter how hard we try, errors do creep into our programs.
 These errors can be grouped into three categories
 Syntax errors
 Run-time errors
 Logic errors
Syntax errors – it 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 - these are usually beyond your program's control. Examples
include: when a variable takes on an unexpected value (divide by zero), or when a
file is not found. Visual Basic allows you to trap such errors and make attempts
to correct them.
Logic errors – these 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.
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 25
Error trapping
 Error handling is essential to all programming applications.
 Any number of run-time errors can occur,
 if your program does not trap them, the VB default action is to
report the error and then terminate the program.
 By placing error-handling code in your program, you can trap a run-
time error, report it
 Sometimes the user will be able to correct the error and
sometimes not, but simply allowing the program to crash is not
acceptable.
Run-time errors
 Run-time errors are trappable
 Error trapping is enabled with the On Error statement:On Error GoTo errlabel
 outline of an example procedure with error trapping.
 Sub SubExample()
[Declare variables, ...]
On Error GoTo HandleErrors
[Procedure code]
Exit Sub
 HandleErrors:
Error handling code]
End Sub
 EXAMPLE PRG: https://www.thevbprogrammer.com/Ch06/06-07-
ErrorHandling.htm
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 26
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 27
General Error Handling Procedure
 The generic code (begins with label HandleErrors) is:
 HandleErrors:Select Case MsgBox(Error(Err.Number), vbCritical +
vbAbortRetryIgnore, "Error Number" + Str(Err.Number))
Case vbAbort
Resume ExitLine
Case vbRetry
Resume
Case vbIgnore
Resume Next
End Select
ExitLine:
Exit Sub
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 28
General Error Handling Procedure
If Abort is selected, we simply exit the procedure. (This is
done using a Resume to the line labeled ExitLine. Recall all
error trapping must be terminated with a Resume statement
of some kind.)
If Retry is selected, the offending program line is retried (in
a real application, you or the user would have to change
something here to correct the condition causing the error).
If Ignore is selected, program operation continues with the
line following the error causing line.
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 29
Sub SubExample()
.
. [Declare variables, ...]
.
On Error GoTo HandleErrors
.
. [Procedure code]
.
Exit Sub
HandleErrors:
Select Case MsgBox(Error(Err.Number), vbCritical + vbAbortRetryIgnore, "Error Number" + Str(Err.Number))
Case vbAbort
Resume ExitLine
Case vbRetry
Resume
Case vbIgnore
Resume Next
End Select
ExitLine:
Exit Sub
End Sub
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 30
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
Printing to the Immediate Window:
You can print directly to the immediate window while an application is
running.
the immediate window, use the Print method: SYNTAX:
Debug.Print [List of variables separated by commas or semi-colons]
• Example:
Place the following statement in the Command1_Click procedure
Debug.Print X; Y
and run the application.
Examine the immediate window. Note how, at each iteration of the loop, the
program prints the value of X and Y.
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 31
breakpoint.
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
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,
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 32
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
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.
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 33
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.
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 34
FILE HANDLING
VB supports files.
File: it is a collection of records
Record: it is a collection of attributes.
Visual Basic provides three types of files:
1. sequential files :Files that must be read in the same
order in which they were written – one after the other with
no skipping around
2. binary files: "unstructured" files which are read from or
written to as series of bytes, where it is up to the
programmer to specify the format of the file
3. random files: files which support "direct access" by
record number
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 35
FILE HANDLING
File operations:
Open
Prepares a file to be processed by the VB program.
App.Path
Supplies the path of your application
FreeFile
Supplies a file number that is not already in use
Input #
Reads fields from a comma-delimited sequential file
Line Input #
Reads a line (up to the carriage return) from a
sequential file
EOF
Tests for end-of-file
Write #
Writes fields to a sequential file in comma-delimited
format
Print #
Writes a formatted line of output to a sequential file
Close #
Closes a file
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 36
file system control
Three of the controls on the ToolBox let you access the computer's
file system. They are
1. DriveListBox
2. DirListBox
3. FileListBox controls
Using these controls, user can traverse the host computer's file
system, locate any folder or files on hard disk
DriveListBox : Displays the names of the drives within and
connected to the PC. DriveListBox control is a combobox-like
control that's automatically filled with your drive's letters and
volume labels The basic property of this control is the drive
property, which set the drive to be initially selected in the control or
returns the user's selection.
DirListBox : Displays the folders of current Drive. The DirListBox
is a special list box that displays a directory tree.The basic property
of this control is the Path property, which is the name of the folder
whose sub folders are displayed in the control.
file system control
 FileListBox : Displays the files of the current folder. The
FileListBox control is a special-purpose ListBox control that
displays all the files in a given director.The basic property
of this control is also called Path, and it's the path name of
the folder whose files are displayed.
 Following figure shows three files controls are used in the
design of Forms that let users explore the entire structure
of their hard disks.
Exploring MS Visual
Basic 6
Copyright 1999 Prentice-Hall, Inc. 37

More Related Content

Similar to Error Control & File Handling in VB

Reaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdfReaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdffashionbigchennai
 
Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make YASHU40
 
GSP 125 Entire Course NEW
GSP 125 Entire Course NEWGSP 125 Entire Course NEW
GSP 125 Entire Course NEWshyamuopten
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxCOMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxmonicafrancis71118
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxCOMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxcargillfilberto
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxCOMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxdrandy1
 
03-inheritance.ppt
03-inheritance.ppt03-inheritance.ppt
03-inheritance.pptSaiM947604
 
Unit iii vb_study_materials
Unit iii vb_study_materialsUnit iii vb_study_materials
Unit iii vb_study_materialsgayaramesh
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#SyedUmairAli9
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01Wingston
 
I am having trouble writing the individual files for part 1, which i.pdf
I am having trouble writing the individual files for part 1, which i.pdfI am having trouble writing the individual files for part 1, which i.pdf
I am having trouble writing the individual files for part 1, which i.pdfmallik3000
 
qtp 9.2 features
qtp 9.2 featuresqtp 9.2 features
qtp 9.2 featureskrishna3032
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769subhasis100
 

Similar to Error Control & File Handling in VB (20)

TDD Training
TDD TrainingTDD Training
TDD Training
 
Visualbasic tutorial
Visualbasic tutorialVisualbasic tutorial
Visualbasic tutorial
 
Reaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdfReaction StatisticsBackgroundWhen collecting experimental data f.pdf
Reaction StatisticsBackgroundWhen collecting experimental data f.pdf
 
Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make Question 1 briefly respond to all the following questions. make
Question 1 briefly respond to all the following questions. make
 
GSP 125 Entire Course NEW
GSP 125 Entire Course NEWGSP 125 Entire Course NEW
GSP 125 Entire Course NEW
 
Visual basic bt0082
Visual basic  bt0082Visual basic  bt0082
Visual basic bt0082
 
Lect1.pptx
Lect1.pptxLect1.pptx
Lect1.pptx
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxCOMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxCOMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxCOMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
 
C programming
C programmingC programming
C programming
 
03-inheritance.ppt
03-inheritance.ppt03-inheritance.ppt
03-inheritance.ppt
 
Unit iii vb_study_materials
Unit iii vb_study_materialsUnit iii vb_study_materials
Unit iii vb_study_materials
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
I am having trouble writing the individual files for part 1, which i.pdf
I am having trouble writing the individual files for part 1, which i.pdfI am having trouble writing the individual files for part 1, which i.pdf
I am having trouble writing the individual files for part 1, which i.pdf
 
Assemblies in asp
Assemblies in aspAssemblies in asp
Assemblies in asp
 
C sharp chap6
C sharp chap6C sharp chap6
C sharp chap6
 
qtp 9.2 features
qtp 9.2 featuresqtp 9.2 features
qtp 9.2 features
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769
 

More from BhuvanaR13

CRYPTOGRAPHY (2).pdf
CRYPTOGRAPHY (2).pdfCRYPTOGRAPHY (2).pdf
CRYPTOGRAPHY (2).pdfBhuvanaR13
 
Linux File System.docx
Linux File System.docxLinux File System.docx
Linux File System.docxBhuvanaR13
 
UNIT I LINUX.docx
UNIT I LINUX.docxUNIT I LINUX.docx
UNIT I LINUX.docxBhuvanaR13
 
networktopology-final.pptx
networktopology-final.pptxnetworktopology-final.pptx
networktopology-final.pptxBhuvanaR13
 
UNIT III_DCN.pdf
UNIT III_DCN.pdfUNIT III_DCN.pdf
UNIT III_DCN.pdfBhuvanaR13
 
UNIT 2_DCN-converted.pdf
UNIT 2_DCN-converted.pdfUNIT 2_DCN-converted.pdf
UNIT 2_DCN-converted.pdfBhuvanaR13
 
UNIT I_DCN.pdf
UNIT I_DCN.pdfUNIT I_DCN.pdf
UNIT I_DCN.pdfBhuvanaR13
 
INTRODUCTION TO MOBILE COMPUTING.pptx
INTRODUCTION TO MOBILE COMPUTING.pptxINTRODUCTION TO MOBILE COMPUTING.pptx
INTRODUCTION TO MOBILE COMPUTING.pptxBhuvanaR13
 
VB6_INTRODUCTION.ppt
VB6_INTRODUCTION.pptVB6_INTRODUCTION.ppt
VB6_INTRODUCTION.pptBhuvanaR13
 
VB6_OBJECTS AND GRAPHICS.ppt
VB6_OBJECTS AND GRAPHICS.pptVB6_OBJECTS AND GRAPHICS.ppt
VB6_OBJECTS AND GRAPHICS.pptBhuvanaR13
 

More from BhuvanaR13 (10)

CRYPTOGRAPHY (2).pdf
CRYPTOGRAPHY (2).pdfCRYPTOGRAPHY (2).pdf
CRYPTOGRAPHY (2).pdf
 
Linux File System.docx
Linux File System.docxLinux File System.docx
Linux File System.docx
 
UNIT I LINUX.docx
UNIT I LINUX.docxUNIT I LINUX.docx
UNIT I LINUX.docx
 
networktopology-final.pptx
networktopology-final.pptxnetworktopology-final.pptx
networktopology-final.pptx
 
UNIT III_DCN.pdf
UNIT III_DCN.pdfUNIT III_DCN.pdf
UNIT III_DCN.pdf
 
UNIT 2_DCN-converted.pdf
UNIT 2_DCN-converted.pdfUNIT 2_DCN-converted.pdf
UNIT 2_DCN-converted.pdf
 
UNIT I_DCN.pdf
UNIT I_DCN.pdfUNIT I_DCN.pdf
UNIT I_DCN.pdf
 
INTRODUCTION TO MOBILE COMPUTING.pptx
INTRODUCTION TO MOBILE COMPUTING.pptxINTRODUCTION TO MOBILE COMPUTING.pptx
INTRODUCTION TO MOBILE COMPUTING.pptx
 
VB6_INTRODUCTION.ppt
VB6_INTRODUCTION.pptVB6_INTRODUCTION.ppt
VB6_INTRODUCTION.ppt
 
VB6_OBJECTS AND GRAPHICS.ppt
VB6_OBJECTS AND GRAPHICS.pptVB6_OBJECTS AND GRAPHICS.ppt
VB6_OBJECTS AND GRAPHICS.ppt
 

Recently uploaded

Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptxDhatriParmar
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17Celine George
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfChristalin Nelson
 
Unit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceUnit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceDr Vijay Vishwakarma
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
 
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...Nguyen Thanh Tu Collection
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
The role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipThe role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipKarl Donert
 
physiotherapy in Acne condition.....pptx
physiotherapy in Acne condition.....pptxphysiotherapy in Acne condition.....pptx
physiotherapy in Acne condition.....pptxAneriPatwari
 
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...DrVipulVKapoor
 
Shark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsShark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsArubSultan
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxMadhavi Dharankar
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptxmary850239
 

Recently uploaded (20)

Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
Unraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptxUnraveling Hypertext_ Analyzing  Postmodern Elements in  Literature.pptx
Unraveling Hypertext_ Analyzing Postmodern Elements in Literature.pptx
 
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
Plagiarism,forms,understand about plagiarism,avoid plagiarism,key significanc...
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdf
 
Unit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceUnit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional Intelligence
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
 
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
The role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenshipThe role of Geography in climate education: science and active citizenship
The role of Geography in climate education: science and active citizenship
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
physiotherapy in Acne condition.....pptx
physiotherapy in Acne condition.....pptxphysiotherapy in Acne condition.....pptx
physiotherapy in Acne condition.....pptx
 
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
Geoffrey Chaucer Works II UGC NET JRF TGT PGT MA PHD Entrance Exam II History...
 
Shark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsShark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristics
 
Objectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptxObjectives n learning outcoms - MD 20240404.pptx
Objectives n learning outcoms - MD 20240404.pptx
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx
 

Error Control & File Handling in VB

  • 1. Unit 3 ERROR CONTROL & FILE HANDLING 1 R. BHUVANESWARI ASST.PROFESSOR DEPT OF COMPUTER SCIENCE AND APPLICATION DKM COLLEGE FOR WOMEN (AUTONOMOUS) VELLORE
  • 2. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 2 Arrays  An array is a consecutive group of memory locations that all have the same name and the same type.  Arrays are programming constructs that store data and allow us to access them by numeric index or subscript  To refer to a particular location or element in the array, we specify the array name and the array element position number. i.e index  Arrays helps us create shorter and simpler code in many situations.  All arrays in VB are zero based, i.e, the index of the first element is zero and they are numbered sequentially.  The upper bound is the number that specifies the index of the last element of the array.  Arrays are declared using Dim, ReDim, Static, Private, Public and Protected keywords.
  • 3. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 3 Array Decleration  The dimensionality of an array refers to the number of subscripts used to identify an individual element.  There are 3 types of array  1. one dimensional array(one index) e.g -A()  2. two dimensional array (two index) e.g A()()  3. multi – dimensional array (more than 2 index) Declaring arrays  Arrays occupy space in memory.  The programmer specifies the array type and the number of elements required by the array  arrays are declared in the general declarations using keyword Dim or Private.  Arrays may be declared as Public also.
  • 4. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 4 Static arrays (fixed array)  There are two types of arrays in Visual Basic namely:  Fixed-size array(static array) : The size of array always remains the same-size doesn't change during the program execution.  Dynamic array : The size of the array can be changed at the run time- size changes during the program execution Fixed-sized Arrays(static array)  When an upper bound is specified in the declaration, a Fixed-array is created.  The upper limit should always be within the range of long data type. Declaring a fixed-array  Dim numbers(5) As Integer  The above declaration creates an array with 6 elements, with index numbers running from 0 to 5.
  • 5. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 5 Dynamic arrays dynamic arrays  when we do not know the size of the array we use dynamic array.  its number of elements can be changed at run time.  E.g  Dim Test() as Integer  Here the size of the array is not specified  Dynamic arrays are arrays that can be dimensioned and re- dimensioned as par the need of the program.  You can declare a dynamic array using the ReDim statement.  The Preserve keyword helps to preserve the data in an existing array, when you resize it. 
  • 6. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 6 Reinitializing Arrays(ReDim)  We can change the size of an array after creating them.  The ReDim statement assigns a completely new array object to the specified array variable.  You use ReDim statement to change the number of elements in an array.  The following lines of code demonstrate that.  This code reinitializes the Test array declared above. 'Reinitializing the array  Dim Test(10) as Integer  ReDim Test(25) as Integer  When using the Redim statement all the data contained in the array is lost.•
  • 7. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 7 preserve keyword in an array  If you want to preserve existing data when reinitializing an array then you should use the Preserve keyword  which looks like this:  Dim Test() as Integer={1,3,5}'declares an array an initializes it with three members  ReDim Preserve Test(25)'resizes the array and retains the data in elements 0 to 2 E.G program with redim and preserve: Dim Test() As Integer = {1, 3, 5} For i = 0 To 2 ListBox1.Items.Add(Test(i)) Next–ReDim Preserve Test(6) Test(3) = 9 Test(4) = 19 Test(5) = 67 For i = 3 To 5 ListBox1.Items.Add(Test(i)) Next Finally the list box consist of 6 items namely 1,3,5,9,19,67
  • 8. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 8 Control Arrays  A control array is a group of controls that share the same name and the same event procedures.  he properties of the controls in the control array can vary  Adding controls with control arrays uses fewer resources than adding multiple control of same type at design time.  A control array can be created only at design time.  You create a control and then assign a numeric, non-negative value to its Index property;  Control arrays are one of the most interesting features of the Visual Basic environment, and they add a lot of flexibility to your programs:  this often dramatically reduces the amount of code you have to write to respond to a user's actions.
  • 9. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 9 CREATING Control Arrays  you can dynamically add new elements to a control array at run time; in other words, you can effectively create new controls that didn't exist at design time.  You create two controls of the same class and assign them an identical Name property. Visual Basic shows a dialog box warning you that there's already a control with that name and asks whether you want to create a control array. Click on the Yes button.  You select a control on the form, press Ctrl+C to copy it to the clipboard, and then press Ctrl+V to paste a new instance of the control, which has the same Name property as the original one. Visual Basic shows the warning mentioned in the previous bullet.
  • 10. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 10 example for control array • Calculator program is an example for control array. • For more information visit: https://www.freetutes.com/learn- vb6/lesson11.html
  • 11. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 11 Procedures in VB • Visual Basic offers different types of procedures • It is a small sections of coding in applications • Visual Basic programs can be broken into smaller logical components called Procedures. • It is useful for repeated operations such as the frequently used calculations, text and control manipulation etc benefits of using procedures: 1. t is easier to debug a program with procedures, because it breaks a program into discrete logical limits. 2. Procedures used in one program can act as building blocks for other programs with slight modifications. Types of procedures: VB supports 2 types of procedures. They are: 1. Sub Procedure 2. Function or Property Procedure. Procedure Sub Procedure Function Procedure Event Procedure General Procedure
  • 12. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 12 • A sub procedure can be placed in standard, class and form modules. • Whenever the procedure is called, the statements between Sub and End Sub are executed. • Header of the sub procedure consist of 3 things 1. scope of the procedure(private/public/static) 2. Name of the procedure 3. Argument list Syntax: [Private | Public] [Static] Sub Procedurename [( arglist)] [ statements] End Sub • Here, arglist is a list of argument names separated by commas(if more than one argument is present). • Each argument acts like a variable in the procedure Types of sub procedure: 1. Event Procedures 2. General Procedures Sub Procedures
  • 13. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 13 Event Procedure:  An event procedure is a procedure block that contains the control's actual name, an underscore(_), and the event name.  The following syntax represents the event procedure for a Form_Load event. Private Sub Form_Load() [statement block] End Sub Event Procedures acquire the declarations as Private by default. General Procedures:  A general procedure is declared when several event procedures perform the same actions.  It is a good programming practice to write common statements in a separate procedure (general procedure) and then call them in the event procedure. To add General procedure:  Select Add Procedure option from the Tools menu, which opens an Add Procedure dialog box as shown in the figure given below. Event Procedure
  • 14. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 14  In the name of the procedure type the Name in textbox  Under Type, Sub is selected to create a Sub procedure, Function to create a Function procedure or Property to create a Property procedure.  Under Scope, Public is selected to create a procedure that can be invoked outside the module, or Private to create a procedure that can be invoked only from within the module. We can also create a new procedure in the current module by typing Sub ProcedureName, Function ProcedureName, or Property ProcedureName in the Code window General Procedure
  • 15. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 15  Functions are same like sub procedures, except they return a value to the calling procedure.  They are especially useful for taking one or more pieces of data, called arguments and performing some tasks with them.  Then the functions returns a value that indicates the results of the tasks complete within the function.  Here Header of the function consist of 3 things 1. Name of the procedure 2. Argument list 3. Return type Example: Function Hypotenuse (A As Double, B As Double) As Double Hypotenuse = sqr (A^2 + B^2) End Function Function Procedures Fun name Arguments list Return type
  • 16. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 16 Property Procedures  property procedure is used to create and manipulate custom properties.  It is used to create read only properties for Forms, Standard modules and Class modules.  Visual Basic provides three kind of property procedures 1. Let procedure - that sets the value of a property, Property 2. Get procedure - that returns the value of a property, and Property 3. Set procedure - that sets the references to an object.
  • 17. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 17 Multiple Forms in Visual Basic  most Visual Basic applications use multiple forms.  To add a form to an application, click the New Form button on the toolbar or select Form under the Insert menu.  On each form we can draw the controls, assign properties, and write code.  You need to decide when and how you want particular forms to be displayed.  The user always interacts with the ‘active’ form.
  • 18. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 18 Multiple Form Example  Start a new application. Put two command buttons on the form (Form1).  Set one’s Caption to Display Form2 and the other’s Caption to Display Form3.  The form will look like this:  Attach this code to the two command buttons Click events. Private Sub Command1_Click() Form2.Show vbModeless End Sub Private Sub Command2_Click() Form3.Show vbModal End Sub Add a second form to the application (Form2). Place a command button on the form. Set its Caption to Hide Form
  • 19. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 19 Multiple Form Example  Atta ch this code to the button’s Click event. Private Sub Command1_Click() Form2.Hide Form1.Show End Sub  Add a third form to the application (Form3).  This form will be modal. Place a command button on the form.  Set its Caption to Hide Form Attach this code to the button’s Click event. Private Sub Command1_Click() Form3.Hide Form1.Show End Sub
  • 20. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 20 Multiple Form Example  Attach this code to the two command buttons Click events.  Private Sub Command1_Click()  Form2.Show vbModeless  End Sub  Private Sub Command2_Click()  Form3.Show vbModal  End Sub  Make sure Form1 is the startup form (check the Project Properties window under the Project menu).  Run the application.
  • 21. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 21 Do events  DoEvents passes control to the operating system  Control is returned after the operating system has finished processing.  The DoEvents function returns an Integer representing the number of open forms in stand-alone versions of Visual Basic.  DoEvents is most useful for simple things like allowing a user to cancel a process after it has started, for example a search for a file.  Example Dim I, For I = 1 To 150000 ' Start loop. If I Mod 1000 = 0 Then ' If loop has repeated 1000 times. OpenForms = DoEvents ' Yield to operating system. End If Next I
  • 22. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 22 Sub-main function  Every Visual Basic application must contain a procedure called Main.  This procedure serves as the starting point and overall control for your application.  Main contains the code that runs first  In Main, you can determine which form is to be loaded first when the program starts. Declaring the Main Procedure Sub Main() MsgBox("The Main procedure is starting the application.") ' Insert call to appropriate starting place in your code. MsgBox("The application is terminating.") End Sub
  • 23. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 23 Sub-main function Sub-main as a function Function Main() As Integer MsgBox("The Main procedure is starting the application.") Dim returnValue As Integer = 0 MsgBox("The application is terminating with error level " & CStr(returnValue) & ".") Return returnValue End Function
  • 24. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 24 Error trapping  No matter how hard we try, errors do creep into our programs.  These errors can be grouped into three categories  Syntax errors  Run-time errors  Logic errors Syntax errors – it 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 - these are usually beyond your program's control. Examples include: when a variable takes on an unexpected value (divide by zero), or when a file is not found. Visual Basic allows you to trap such errors and make attempts to correct them. Logic errors – these 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.
  • 25. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 25 Error trapping  Error handling is essential to all programming applications.  Any number of run-time errors can occur,  if your program does not trap them, the VB default action is to report the error and then terminate the program.  By placing error-handling code in your program, you can trap a run- time error, report it  Sometimes the user will be able to correct the error and sometimes not, but simply allowing the program to crash is not acceptable.
  • 26. Run-time errors  Run-time errors are trappable  Error trapping is enabled with the On Error statement:On Error GoTo errlabel  outline of an example procedure with error trapping.  Sub SubExample() [Declare variables, ...] On Error GoTo HandleErrors [Procedure code] Exit Sub  HandleErrors: Error handling code] End Sub  EXAMPLE PRG: https://www.thevbprogrammer.com/Ch06/06-07- ErrorHandling.htm Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 26
  • 27. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 27 General Error Handling Procedure  The generic code (begins with label HandleErrors) is:  HandleErrors:Select Case MsgBox(Error(Err.Number), vbCritical + vbAbortRetryIgnore, "Error Number" + Str(Err.Number)) Case vbAbort Resume ExitLine Case vbRetry Resume Case vbIgnore Resume Next End Select ExitLine: Exit Sub
  • 28. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 28 General Error Handling Procedure If Abort is selected, we simply exit the procedure. (This is done using a Resume to the line labeled ExitLine. Recall all error trapping must be terminated with a Resume statement of some kind.) If Retry is selected, the offending program line is retried (in a real application, you or the user would have to change something here to correct the condition causing the error). If Ignore is selected, program operation continues with the line following the error causing line.
  • 29. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 29 Sub SubExample() . . [Declare variables, ...] . On Error GoTo HandleErrors . . [Procedure code] . Exit Sub HandleErrors: Select Case MsgBox(Error(Err.Number), vbCritical + vbAbortRetryIgnore, "Error Number" + Str(Err.Number)) Case vbAbort Resume ExitLine Case vbRetry Resume Case vbIgnore Resume Next End Select ExitLine: Exit Sub End Sub
  • 30. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 30 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 Printing to the Immediate Window: You can print directly to the immediate window while an application is running. the immediate window, use the Print method: SYNTAX: Debug.Print [List of variables separated by commas or semi-colons] • Example: Place the following statement in the Command1_Click procedure Debug.Print X; Y and run the application. Examine the immediate window. Note how, at each iteration of the loop, the program prints the value of X and Y.
  • 31. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 31 breakpoint. 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 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,
  • 32. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 32 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 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.
  • 33. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 33 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.
  • 34. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 34 FILE HANDLING VB supports files. File: it is a collection of records Record: it is a collection of attributes. Visual Basic provides three types of files: 1. sequential files :Files that must be read in the same order in which they were written – one after the other with no skipping around 2. binary files: "unstructured" files which are read from or written to as series of bytes, where it is up to the programmer to specify the format of the file 3. random files: files which support "direct access" by record number
  • 35. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 35 FILE HANDLING File operations: Open Prepares a file to be processed by the VB program. App.Path Supplies the path of your application FreeFile Supplies a file number that is not already in use Input # Reads fields from a comma-delimited sequential file Line Input # Reads a line (up to the carriage return) from a sequential file EOF Tests for end-of-file Write # Writes fields to a sequential file in comma-delimited format Print # Writes a formatted line of output to a sequential file Close # Closes a file
  • 36. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 36 file system control Three of the controls on the ToolBox let you access the computer's file system. They are 1. DriveListBox 2. DirListBox 3. FileListBox controls Using these controls, user can traverse the host computer's file system, locate any folder or files on hard disk DriveListBox : Displays the names of the drives within and connected to the PC. DriveListBox control is a combobox-like control that's automatically filled with your drive's letters and volume labels The basic property of this control is the drive property, which set the drive to be initially selected in the control or returns the user's selection. DirListBox : Displays the folders of current Drive. The DirListBox is a special list box that displays a directory tree.The basic property of this control is the Path property, which is the name of the folder whose sub folders are displayed in the control.
  • 37. file system control  FileListBox : Displays the files of the current folder. The FileListBox control is a special-purpose ListBox control that displays all the files in a given director.The basic property of this control is also called Path, and it's the path name of the folder whose files are displayed.  Following figure shows three files controls are used in the design of Forms that let users explore the entire structure of their hard disks. Exploring MS Visual Basic 6 Copyright 1999 Prentice-Hall, Inc. 37

Editor's Notes

  1. Exploring Microsoft Visual Basic 6.0