Upload
reynard-cameron
View
215
Download
0
Embed Size (px)
Citation preview
Saeed GhanbartehraniSummer 2015
Lecture Notes #6:
Function Procedures & Arrays
IE 212: Computational Methods for Industrial Engineering
2
Overview
Organizing Sub Procedures
Creating Function Procedures
Methods to Pass Variables in Sub and Function Procedures
Public and Private Procedures
Using Arrays in Excel VBA
Summary
3
Organizing Sub Procedures
You should group various actions into several smaller sub procedures rather than having one large sub procedure in which the entire program is written– Allows for programs to run more efficiently– Promotes code reusability
The ideal module structure for your program is to have one Main() sub procedure from which other sub procedures are called– This Main macro will usually be assigned to a “Start” button on the
“Welcome” sheet
To call another sub procedure, we use the command Call followed by the sub procedure name
4
Organizing Sub Procedures (cont.)
For example, consider three different sub procedures, called GetInput(), Calculations(), and DisplayResults()
We can then call these three sub procedures from the Main() sub procedure as follows
Sub Main()
Call GetInput
Call Calculations
Call DisplayResults
End Sub
You can also call other sub procedures from these three sub procedures
5
Function Procedures
A function procedure is a type of procedure that can take arguments and execute a series of statements
A function procedure differs from a sub procedure in that– It is invoked through its name– It returns a single value
Critical elements when writing a function procedure– The name of the function– The type of the function
6
Function Procedures (cont.)
Syntax of a function procedureFunction name ([arglist])
[statements][name = expression][Exit Function][statements][name = expression]
End Function
A function procedure can be called from any sub procedure or any other function procedure
Function FunctionName()
….
End Function
7
Function Procedures (cont.)
To illustrate the proper use of a function in Excel VBA, we will use an example where the sum of two values is calculated – We will use AddTwoNumbers as the name of the function
8
Function Procedures (cont.)
The function itself is quite simple in this case
To return a value from a function in Excel VBA, you should assign a value to the name of the function procedure
The variables x and y in this example do not need to be declared– They are the variables used throughout the function procedure
9
Function Procedures (cont.)
The variables x and y in the function AddTwoNumbers will assume the respective data types assigned to a and b– If we had defined the function AddTwoNumbers with data types in
the argument, we would be restricted to only passing variables of that data type
– Function AddTwoNumbers(x As Integer, y As Integer)
Notice also that the variable names used as arguments when the function is called and the variable names used in the function procedure statement do not need to be the same– a and b in Sub procedure– x and y in Function procedure
10
Methods to Pass Variables
There are two methods to pass variables in sub procedures and function procedures– By reference (default)– By value
Passing a value by reference implies that the procedure (or function) can access and possibly modify the original value assigned to the variable
Passing by value provides a copy of the value of the variable for the procedure or function to use– Therefore, the original value of the variable remains intact
11
Methods to Pass Variables (cont.)
To pass a variable by value, we must use the keyword ByVal when defining the arguments that the function will take
Function AddTwoNumbers(ByVal x, ByVal y)
AddTwoNumbers = x + y
End Function
Alternatively, a variable can be passed by value by enclosing it in parentheses when the sub procedure or function is called
Call Multiply((i), j) Sub procedure
result = Multiply((a), (b)) Function procedure
12
Public and Private Procedures
The scope of a sub procedure, like a variable, can also be defined as Public or Private
A private sub procedure is declared by putting the word Private before the Sub statement– Private sub procedures can only be called from procedures in the
same module– Private sub procedures are not listed when you try to run a macro in
Excel
A public sub procedure can be called from any other procedure– The word Public can be put in front of the Sub statement, or the Sub
statement can be written without a preceding statement
13
Using Arrays in Excel VBA
14
Introduction to Arrays in Excel VBA
Arrays store series of data elements that can be manipulated or referred to later– Arrays are very useful when we need to perform the same operation
(or a series of operations) on a group of values– Arrays may also make programs more compact (and possibly more
efficient) For example, if we know a program’s output will be 3 integer variables,
we can store these values in an integer array of size 3
The set of data elements stored in an array must all be of the same data type
15
Declaring Arrays
To declare an array, the variable declaration keywords Dim, Private, or Public can be used
VBA will recognize a variable as an array and not a scalar variable because a set of parentheses (and, in some cases, the size of the array) is included in the variable declaration– Dim stdNames(10) As String– Dim stdGrades() As Integers
This is how the one-dimensional array tempData, containing 10 elements of data type Double, is declared– Dim tempData(9) As Double
16
Declaring Arrays (cont.)
For a one-dimensional array, a single number is all that is necessary to specify the size
To declare multi-dimensional arrays, you need to specify the size of each dimension (i.e., rows and columns), separated by a comma– Dim data(2, 3) As Double
17
Arrays’ Indices
You can refer to the individual elements in an array using an index value– When an array is declared in Excel VBA, a default index is assigned
to each element
The default index of the first element in a one-dimensional array is 0
The default index of the first element in a two-dimensional array is 0,0
18
Arrays’ Indices (cont.)
Examples
2.01 3.81 1.09 4.44 2.19 2.03expData( ) =
"IE212" "IE368" "IE411"
"IE418" "IE419" "IE475"
myOSUCourses ( , ) =
19
Arrays’ Indices (cont.)
You can instruct Excel VBA to change the default index values of all arrays in your module with the instruction Option Base 1– One dimensional arrays will begin at 1– Two-dimensional arrays will begin at 1,1
Option Base 1Dim data(10) As Double, results(12) As Double
If you want to keep the default initial index as 0 but would like a specific array to start with a different index, you can specify the starting index value in the array declaration – Dim data(1 To 10) As Long, results(12) As Double– Dim matrix(1 To 20, 1 To 10) As Double
20
Arrays’ Indices (cont.)
In the last case, just be aware of the size of your array– Dim results(2 to 13) As Double– size = upper index bound – lower index bound + 1
Whichever initial index value is chosen, it should be coordinated with the counter variable used in For…Next loops
For i = 1 To 13
results(i) = value
Next i
21
Arrays’ Indices (cont.)
LBound Function– Returns a Long containing the smallest available subscript for the
indicated dimension of an array– Syntax LBound(arrayname [, dimension])
UBound Function– Returns a Long containing the largest available subscript for the
indicated dimension of an array– Syntax UBound(arrayname [, dimension])
Dim A(1 To 100, 0 To 3) as Integer
LBound(A, 1) UBound(A, 1) LBound(A, 2) UBound(A, 2)
22
Populating Arrays with Values
To assign a value of a specific element of the array, we use the index of the element– For example, to assign a value of 10.5 to the third member of array
data(9), we would type data(2) = 10.5
To set multiple values of an array, it is more practical to use a For…Next loop with a counter variable
For example, to set each element in the array data(9) equal to its index number, we would type
For i = LBound(data) To UBound(data)
data(i) = i
Next i
23
Populating Arrays with Values (cont.)
To assign values to the elements of a multi-dimensional array or to search for a value, use nested For…Next loops with different counter variables
For example, to set the value of each element in the two-dimensional array data(4, 9) equal to the product of its indices, you would do the following:
0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9
0 2 4 6 8 10 12 14 16 18
0 3 6 9 12 15 18 21 24 27
0 4 8 12 16 20 24 28 32 36
24
Dynamic Arrays
If you are not sure about the size of an array at declaration time, you can use a dynamic array declaration– For example, sometimes we expect the user to tell our application
how many elements the array should have
When declaring a dynamic array, the array size is not specified and the parentheses are left empty– Dim input() As Double
However, before this array or any of its elements is used, we must (eventually) know its size and declare it accordingly
25
Dynamic Arrays (cont.)
To set the size of a dynamic array at some later point in the code, we use the ReDim statement
The ReDim statement can also be used to set or change the number of dimensions and the indexing bounds– Suppose we want to ask the user to provide input values, which we
will store in our array input
26
Dynamic Arrays (cont.)
If you want to change the size of a dynamic array but do not want to reset its values, then use the statement ReDim Preserve– Suppose we have a dynamic array of size 9 which has already been
populated with values and we need to add one more value
To keep the current values in the array but add one more element, we type
ReDim Preserve input(10)
input(10) = InputBox(“Please enter new value.”)
27
Summary
To call another sub procedure, use the command Call followed by the sub procedure name
Function procedures are similar to sub procedures and follow this basic structure:
Function FunctionName()
….
End Function
28
Summary (cont.)
To pass a variable in Excel VBA, you should insert the variable as an argument/parameter of the function when it is called
A sub procedure, like a variable, can also be defined as Public or Private
29
Summary (cont.)
Arrays store series of data that we can manipulate or refer to later
To define an array, use the Dim, Private, or Public variable declarations– For a one-dimensional array, we just need a single number to specify
the size– To define multi-dimensional arrays, we must specify the size of each
dimension, separated by a comma
The default initial index value of arrays in VBA is 0
To change the initial index value of all arrays in our module to 1, type Option Base 1 at the top of the module
30
Summary (cont.)
To set the size of a dynamic array at some later point in the code, use the ReDim statement
The ReDim Preserve statement retains any previously assigned element values– Only works with dynamic arrays