SlideShare a Scribd company logo
1 of 21
Download to read offline
PROCEDURES
Procedures - Modules and Procedures; Sub Procedures; Event
Procedures; Function Procedures; Scope; Optional Arguments.
Arrays - Characteristics; Declarations;
Processing; Passing Arrays to Procedures; Dynamic Arrays;
Array-related Functions; Control Arrays ; Looping with for
Each-Next.
PROCEDURES - MODULES AND PROCEDURES
 A project may also include a standard module. Standard modules contain declarations and
procedures that can be accessed by other modules. Standard modules are stored as files with
the extension .bas. A standard module can be created by selecting Add Module from Visual
Basic’s Project menu. This results in a new code editor window, within which you may add
the necessary declarations and procedures.
 Visual Basic also supports other types of modules, including class modules (extension .cls),
whose characteristics are beyond the scope of our present discussion.
 A procedure (including an event procedure) is a self-contained group of Visual Basic
commands that can be accessed from a remote location within a Visual Basic program. The
procedure then carries out some specific action. Information can be freely transferred
between the “calling” location (i.e., the command which accesses the procedure) and the
procedure itself.
PROCEDURES - MODULES AND PROCEDURES
 Visual Basic supports three types of procedures – Sub procedures (sometimes referred to simply as
subroutines), Function procedures (also called functions), and Property procedures. Sub and
function procedures are commonly used in beginning and intermediate level programs. Hence, our
focus in this chapter will be on sub and function procedures. The shell (beginning and ending
statements) for a new sub or function procedure can be added to a project by selecting Add
Procedure... from the Tools menu.
 Example: SUB PROCEDURES (SUBROUTINES)
In its simplest form, a sub procedure is written as
Sub procedure name (arguments)
. . . . .
statements
. . . . .
End Sub
EXAMPLE: DEFINING A SUB PROCEDURE
Here is a sub procedure that determines the smallest of two numbers.
Sub Smallest(a, b)
Dim Min
If (a < b) Then
Min = a
MsgBox "a is smaller (a = " & Str(Min) & ")"
ElseIf (a > b) Then
Min = b
MsgBox "b is smaller (b = " & Str(Min) & ")"
Else
Min = a
MsgBox "Both values are equal (a, b = " & Str(Min) & ")"
End If
End Sub
EVENT PROCEDURE
 An event procedure is a special type of sub procedure. It is accessed by some specific action,
such as clicking on an object, rather than by the Call statement or by referring to the
procedure name. The particular action associated with each event procedure is selected from
the upper-right drop-down menu within the Code Editor Window. The object name and the
activating event collectively make up the event procedure name. Thus, Command1_Click().
 EXAMPLE DEFINING AN EVENT PROCEDURE
FUNCTION PROCEDURE
 A function procedure is similar to a sub procedure, with one important difference: a function
is intended to return a single data item, just as a library function returns a single data item.
Each function name therefore represents a data item, and has a data type associated with it.
Within a function definition, the function name must be assigned the value to be returned, as
though the function name were an ordinary variable.
 In its simplest form, a function procedure is written as
Function procedure name (arguments) As data type
. . . . .
statements
. . . . .
procedure name = . . . . .
. . . . .
End Function
SCOPE
 Scope refers to the portion of a program within which a procedure definition (or a variable or
named constant definition) is recognized. The scope of a sub procedure is determined by the
identifier Public or Private, which precedes the procedure name; e.g.,
Public Sub procedure name (arguments)
or
Private Sub procedure name (arguments)
Similarly, the scope of a function procedure is determined as
Public Function procedure name (arguments) As data type
or
Private Function procedure name (arguments) As data type
OPTIONAL ARGUMENTS
 When accessing a procedure, the passing of one or more arguments can be made optional. To
do so, each optional argument declaration within the first line of the procedure definition must
be preceded by the keyword Optional. For example, if a sub procedure is defined with one
mandatory argument and one optional argument, the first line of the procedure declaration
will be
Sub procedure name (argument1 As data type1, Optional argument2 As data type2)
 A default value may be specified for each optional argument, by writing
Optional argument As data type = value
 The default value will be assigned to the argument if an actual argument value is not provided
in the procedure reference.
ARRAYS - CHARACTERISTICS
 Many applications require the processing of multiple data items that have common
characteristics, such. as a set of numerical data items represented by x1, x2, . . ., xn
 Each individual array element (i.e., each individual data item) is referred to by specifying
the array name followed by one or more subscripts, enclosed in parentheses. Each
subscript is expressed as an integer quantity, beginning with 0. Thus, in the n-element array
x, the array elements are x(0), x(1), . . . , x(n − 1).
one-dimensional array
Similarly, y(i, j) refers to an element in the two-dimensional array y. Think of a two-
dimensional array as a table, where i refers to the row number and j refers to the column
number Two-dimensional array
ARRAY DECLARATIONS
 An array must be declared before it can appear within an executable statement. The Dim statement
is used for this purpose. This statement defines the dimensionality (i.e., the number of subscripts),
the size (range of each subscript), the data type and the scope of an array.
 To declare an array within a procedure, the Dim statement is generally written as
Dim array name (subscript 1 upper limit, subscript 2 upper limit, etc.) As data type
 Within a module (but outside of a procedure), array declarations are written as
Private array name (subscript 1 upper limit, subscript 2 upper limit, etc.) As data type
or
Public array name (subscript 1 upper limit, subscript 2 upper limit, etc.) As data type
 EXAMPLE
 A Visual Basic module includes the following array declarations.
DIM Customers(200) As String, Net(100) As Single, Sales(1 To 50, 1 To 100) As Single
PROCESSING ARRAY ELEMENTS (SUBSCRIPTED VARIABLES)
 The individual elements within an array are called subscripted variables. Subscripted
variables can be utilized within a program in the same manner as ordinary variables.
 A subscripted variable can be accessed by writing the array name, followed by the value of
the subscript enclosed in parentheses. Multidimensional array elements require the
specification of multiple subscripts, separated by commas. The subscripts must be integer
valued and they must fall within the range specified by the corresponding array declaration.
 A subscript can be written as a constant, a variable or a numeric expression. Non-integer
values will automatically be rounded, as required. If the value of a subscript is out of range
(i.e., too large or too small), execution of the program will be suspended and an error
message will appear.
 Now consider the event procedure associated with the combo box.
Private Sub Combo1_Click()
Dim Hello(6) As String
'assign the array elements
Hello(0) = "Bonjour"
Hello(1) = "Guten Tag"
Hello(2) = "Aloha"
Hello(3) = "Shalom"
Hello(4) = "Buon Giorno"
Hello(5) = "Konichihua"
Hello(6) = "Buenos Dias"
'assign one array element to the text box
Text1.Text = Hello(Combo1.ListIndex)
End Sub
PASSING ARRAYS TO PROCEDURES
 Arrays can be passed to procedures as arguments, in much the same manner as ordinary
variables are passed as arguments. If an argument is an array, however, an empty pair of
parentheses must follow the array name. This requirement must be satisfied in both the
procedure access and the first line of the procedure definition, as illustrated in the following
example
Dim x(10) As Integer, n As Integer
. . . . .
n = . . . . .
Call Setup(x(), n) 'procedure reference
'or Setup x(), n
Private Sub Setup(v() As Integer, n As Integer) 'procedure definition
Dim i As Integer
For i = 0 to n
v(i) = i ^ 2
Next i
End Sub
DYNAMIC ARRAYS
 Dynamic arrays differ from fixed arrays because a subscript range for the array elements is
not specified when the array is dimensioned. Instead, the subscript range is set using the
ReDim statement. With dynamic arrays, the number of array elements can be set based on
other conditions in your procedure. For example, you may want to use an array to store a
set of values entered by the user, but you may not know in advance how many values the
user will enter. In this case, you dimension the array without specifying a subscript range
and then execute a ReDim statement each time the user enters a new value. Or you may
want to prompt for the number of values to be entered and execute one ReDim statement to
set the size of the array before prompting for the values.
CONTROL ARRAYS AND USER DEFINED PROCEDURES
 A control array is a group of controls that share the same name type and the same event
procedures. 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, and at
the very minimum at least one control must belong to it. You create a control array following
one of these three methods:
 You create a control and then assign a numeric, non-negative value to its index property; you
have thus created a control array with just one element.
 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.
Control arrays are one of the most interesting features of the Visual Basic environment,
and they add a lot of flexibility to your programs:
•Controls that belong to the same control array share the same set of event procedures; this
often dramatically reduces the amount of code you have to write to respond to a user's
actions.
•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.
•Elements of control arrays consume fewer resources than regular controls and tend to
produce smaller executables. Besides, Visual Basic forms can host up to 256 different
control names, but a control array counts as one against this number. In other words,
control arrays let you effectively overcome this limit.
LOOPING WITH FOR EACH-NEXT
 When a For Each…Next statement runs, Visual Basic evaluates the collection only one
time, before the loop starts. If your statement block changes element or group, these changes
don't affect the iteration of the loop.
 When all the elements in the collection have been successively assigned to element, the For
Each loop stops and control passes to the statement following the Next statement.
 If element hasn't been declared outside this loop, you must declare it in the For
Each statement. You can declare the type of element explicitly by using an As statement, or
you can rely on type inference to assign the type. In either case, the scope of element is the
body of the loop. However, you cannot declare element both outside and inside the loop.
 You can optionally specify element in the Next statement. This improves the readability of
your program, especially if you have nested For Each loops. You must specify the same
variable as the one that appears in the corresponding For Each statement
procedures and arrays

More Related Content

Similar to procedures and arrays

Chapter 6 slides
Chapter 6 slidesChapter 6 slides
Chapter 6 slidesjdpike
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01Wingston
 
PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...
PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...
PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...Khushboo Jain
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
MuleSoft Nashik Virtual Meetup#3 - Deep Dive Into DataWeave and its Module
MuleSoft Nashik Virtual  Meetup#3 - Deep Dive Into DataWeave and its ModuleMuleSoft Nashik Virtual  Meetup#3 - Deep Dive Into DataWeave and its Module
MuleSoft Nashik Virtual Meetup#3 - Deep Dive Into DataWeave and its ModuleJitendra Bafna
 
Introduction to System verilog
Introduction to System verilog Introduction to System verilog
Introduction to System verilog Pushpa Yakkala
 
Complete list of all sap abap keywords
Complete list of all sap abap keywordsComplete list of all sap abap keywords
Complete list of all sap abap keywordsPrakash Thirumoorthy
 
Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Ali Raza Zaidi
 
Vb6 ch.8-3 cci
Vb6 ch.8-3 cciVb6 ch.8-3 cci
Vb6 ch.8-3 cciFahim Khan
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...vekariyakashyap
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variablesSaurav Kumar
 

Similar to procedures and arrays (20)

Chapter 6 slides
Chapter 6 slidesChapter 6 slides
Chapter 6 slides
 
Introduction to Visual Basic
Introduction to Visual Basic Introduction to Visual Basic
Introduction to Visual Basic
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...
PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...
PPT ON VHDL subprogram,package,alias,use,generate and concurrent statments an...
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
MuleSoft Nashik Virtual Meetup#3 - Deep Dive Into DataWeave and its Module
MuleSoft Nashik Virtual  Meetup#3 - Deep Dive Into DataWeave and its ModuleMuleSoft Nashik Virtual  Meetup#3 - Deep Dive Into DataWeave and its Module
MuleSoft Nashik Virtual Meetup#3 - Deep Dive Into DataWeave and its Module
 
Introduction to System verilog
Introduction to System verilog Introduction to System verilog
Introduction to System verilog
 
Complete list of all sap abap keywords
Complete list of all sap abap keywordsComplete list of all sap abap keywords
Complete list of all sap abap keywords
 
Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3Microsoft dynamics ax 2012 development introduction part 2/3
Microsoft dynamics ax 2012 development introduction part 2/3
 
Java execise
Java execiseJava execise
Java execise
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Vb6 ch.8-3 cci
Vb6 ch.8-3 cciVb6 ch.8-3 cci
Vb6 ch.8-3 cci
 
MA3696 Lecture 9
MA3696 Lecture 9MA3696 Lecture 9
MA3696 Lecture 9
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variables
 
Generics
GenericsGenerics
Generics
 
Bt0065
Bt0065Bt0065
Bt0065
 
B T0065
B T0065B T0065
B T0065
 

Recently uploaded

IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptSAURABHKUMAR892774
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIkoyaldeepu123
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 

Recently uploaded (20)

IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Arduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.pptArduino_CSE ece ppt for working and principal of arduino.ppt
Arduino_CSE ece ppt for working and principal of arduino.ppt
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
EduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AIEduAI - E learning Platform integrated with AI
EduAI - E learning Platform integrated with AI
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 

procedures and arrays

  • 1. PROCEDURES Procedures - Modules and Procedures; Sub Procedures; Event Procedures; Function Procedures; Scope; Optional Arguments. Arrays - Characteristics; Declarations; Processing; Passing Arrays to Procedures; Dynamic Arrays; Array-related Functions; Control Arrays ; Looping with for Each-Next.
  • 2. PROCEDURES - MODULES AND PROCEDURES  A project may also include a standard module. Standard modules contain declarations and procedures that can be accessed by other modules. Standard modules are stored as files with the extension .bas. A standard module can be created by selecting Add Module from Visual Basic’s Project menu. This results in a new code editor window, within which you may add the necessary declarations and procedures.  Visual Basic also supports other types of modules, including class modules (extension .cls), whose characteristics are beyond the scope of our present discussion.  A procedure (including an event procedure) is a self-contained group of Visual Basic commands that can be accessed from a remote location within a Visual Basic program. The procedure then carries out some specific action. Information can be freely transferred between the “calling” location (i.e., the command which accesses the procedure) and the procedure itself.
  • 3. PROCEDURES - MODULES AND PROCEDURES  Visual Basic supports three types of procedures – Sub procedures (sometimes referred to simply as subroutines), Function procedures (also called functions), and Property procedures. Sub and function procedures are commonly used in beginning and intermediate level programs. Hence, our focus in this chapter will be on sub and function procedures. The shell (beginning and ending statements) for a new sub or function procedure can be added to a project by selecting Add Procedure... from the Tools menu.  Example: SUB PROCEDURES (SUBROUTINES) In its simplest form, a sub procedure is written as Sub procedure name (arguments) . . . . . statements . . . . . End Sub
  • 4. EXAMPLE: DEFINING A SUB PROCEDURE Here is a sub procedure that determines the smallest of two numbers. Sub Smallest(a, b) Dim Min If (a < b) Then Min = a MsgBox "a is smaller (a = " & Str(Min) & ")" ElseIf (a > b) Then Min = b MsgBox "b is smaller (b = " & Str(Min) & ")" Else Min = a MsgBox "Both values are equal (a, b = " & Str(Min) & ")" End If End Sub
  • 5. EVENT PROCEDURE  An event procedure is a special type of sub procedure. It is accessed by some specific action, such as clicking on an object, rather than by the Call statement or by referring to the procedure name. The particular action associated with each event procedure is selected from the upper-right drop-down menu within the Code Editor Window. The object name and the activating event collectively make up the event procedure name. Thus, Command1_Click().  EXAMPLE DEFINING AN EVENT PROCEDURE
  • 6. FUNCTION PROCEDURE  A function procedure is similar to a sub procedure, with one important difference: a function is intended to return a single data item, just as a library function returns a single data item. Each function name therefore represents a data item, and has a data type associated with it. Within a function definition, the function name must be assigned the value to be returned, as though the function name were an ordinary variable.  In its simplest form, a function procedure is written as Function procedure name (arguments) As data type . . . . . statements . . . . . procedure name = . . . . . . . . . . End Function
  • 7. SCOPE  Scope refers to the portion of a program within which a procedure definition (or a variable or named constant definition) is recognized. The scope of a sub procedure is determined by the identifier Public or Private, which precedes the procedure name; e.g., Public Sub procedure name (arguments) or Private Sub procedure name (arguments) Similarly, the scope of a function procedure is determined as Public Function procedure name (arguments) As data type or Private Function procedure name (arguments) As data type
  • 8. OPTIONAL ARGUMENTS  When accessing a procedure, the passing of one or more arguments can be made optional. To do so, each optional argument declaration within the first line of the procedure definition must be preceded by the keyword Optional. For example, if a sub procedure is defined with one mandatory argument and one optional argument, the first line of the procedure declaration will be Sub procedure name (argument1 As data type1, Optional argument2 As data type2)  A default value may be specified for each optional argument, by writing Optional argument As data type = value  The default value will be assigned to the argument if an actual argument value is not provided in the procedure reference.
  • 9. ARRAYS - CHARACTERISTICS  Many applications require the processing of multiple data items that have common characteristics, such. as a set of numerical data items represented by x1, x2, . . ., xn  Each individual array element (i.e., each individual data item) is referred to by specifying the array name followed by one or more subscripts, enclosed in parentheses. Each subscript is expressed as an integer quantity, beginning with 0. Thus, in the n-element array x, the array elements are x(0), x(1), . . . , x(n − 1). one-dimensional array
  • 10. Similarly, y(i, j) refers to an element in the two-dimensional array y. Think of a two- dimensional array as a table, where i refers to the row number and j refers to the column number Two-dimensional array
  • 11. ARRAY DECLARATIONS  An array must be declared before it can appear within an executable statement. The Dim statement is used for this purpose. This statement defines the dimensionality (i.e., the number of subscripts), the size (range of each subscript), the data type and the scope of an array.  To declare an array within a procedure, the Dim statement is generally written as Dim array name (subscript 1 upper limit, subscript 2 upper limit, etc.) As data type  Within a module (but outside of a procedure), array declarations are written as Private array name (subscript 1 upper limit, subscript 2 upper limit, etc.) As data type or Public array name (subscript 1 upper limit, subscript 2 upper limit, etc.) As data type  EXAMPLE  A Visual Basic module includes the following array declarations. DIM Customers(200) As String, Net(100) As Single, Sales(1 To 50, 1 To 100) As Single
  • 12. PROCESSING ARRAY ELEMENTS (SUBSCRIPTED VARIABLES)  The individual elements within an array are called subscripted variables. Subscripted variables can be utilized within a program in the same manner as ordinary variables.  A subscripted variable can be accessed by writing the array name, followed by the value of the subscript enclosed in parentheses. Multidimensional array elements require the specification of multiple subscripts, separated by commas. The subscripts must be integer valued and they must fall within the range specified by the corresponding array declaration.  A subscript can be written as a constant, a variable or a numeric expression. Non-integer values will automatically be rounded, as required. If the value of a subscript is out of range (i.e., too large or too small), execution of the program will be suspended and an error message will appear.
  • 13.
  • 14.  Now consider the event procedure associated with the combo box. Private Sub Combo1_Click() Dim Hello(6) As String 'assign the array elements Hello(0) = "Bonjour" Hello(1) = "Guten Tag" Hello(2) = "Aloha" Hello(3) = "Shalom" Hello(4) = "Buon Giorno" Hello(5) = "Konichihua" Hello(6) = "Buenos Dias" 'assign one array element to the text box Text1.Text = Hello(Combo1.ListIndex) End Sub
  • 15. PASSING ARRAYS TO PROCEDURES  Arrays can be passed to procedures as arguments, in much the same manner as ordinary variables are passed as arguments. If an argument is an array, however, an empty pair of parentheses must follow the array name. This requirement must be satisfied in both the procedure access and the first line of the procedure definition, as illustrated in the following example Dim x(10) As Integer, n As Integer . . . . . n = . . . . . Call Setup(x(), n) 'procedure reference 'or Setup x(), n Private Sub Setup(v() As Integer, n As Integer) 'procedure definition Dim i As Integer For i = 0 to n v(i) = i ^ 2 Next i End Sub
  • 16. DYNAMIC ARRAYS  Dynamic arrays differ from fixed arrays because a subscript range for the array elements is not specified when the array is dimensioned. Instead, the subscript range is set using the ReDim statement. With dynamic arrays, the number of array elements can be set based on other conditions in your procedure. For example, you may want to use an array to store a set of values entered by the user, but you may not know in advance how many values the user will enter. In this case, you dimension the array without specifying a subscript range and then execute a ReDim statement each time the user enters a new value. Or you may want to prompt for the number of values to be entered and execute one ReDim statement to set the size of the array before prompting for the values.
  • 17.
  • 18. CONTROL ARRAYS AND USER DEFINED PROCEDURES  A control array is a group of controls that share the same name type and the same event procedures. 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, and at the very minimum at least one control must belong to it. You create a control array following one of these three methods:  You create a control and then assign a numeric, non-negative value to its index property; you have thus created a control array with just one element.  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.
  • 19. Control arrays are one of the most interesting features of the Visual Basic environment, and they add a lot of flexibility to your programs: •Controls that belong to the same control array share the same set of event procedures; this often dramatically reduces the amount of code you have to write to respond to a user's actions. •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. •Elements of control arrays consume fewer resources than regular controls and tend to produce smaller executables. Besides, Visual Basic forms can host up to 256 different control names, but a control array counts as one against this number. In other words, control arrays let you effectively overcome this limit.
  • 20. LOOPING WITH FOR EACH-NEXT  When a For Each…Next statement runs, Visual Basic evaluates the collection only one time, before the loop starts. If your statement block changes element or group, these changes don't affect the iteration of the loop.  When all the elements in the collection have been successively assigned to element, the For Each loop stops and control passes to the statement following the Next statement.  If element hasn't been declared outside this loop, you must declare it in the For Each statement. You can declare the type of element explicitly by using an As statement, or you can rely on type inference to assign the type. In either case, the scope of element is the body of the loop. However, you cannot declare element both outside and inside the loop.  You can optionally specify element in the Next statement. This improves the readability of your program, especially if you have nested For Each loops. You must specify the same variable as the one that appears in the corresponding For Each statement