Introduduction To Financial Programming
Introduduction To Financial Programming
Antonio Rivela
first edition
INDEX
1.
INTRODUCTION TO MATLAB/OCTAVE ............................................................................... 6
1.1.
Matrices as Fundamental Objects ................................................................................... 7
1.2.
Matrix Operations ............................................................................................................ 7
1.3.
Assignment Statements .................................................................................................. 8
1.4.
Case Sensitivity ............................................................................................................... 8
1.5.
Immediate and Deferred Execution................................................................................. 9
1.6.
Showing Values............................................................................................................. 10
1.7.
Initializing Matrices ........................................................................................................ 10
1.8.
Making Matrices from Matrices ..................................................................................... 11
1.9.
Using Portions of Matrices ............................................................................................ 12
1.10.
Text Strings ................................................................................................................... 13
1.11.
Matrix and Array Operations ......................................................................................... 14
1.12.
Matrix Operations .......................................................................................................... 15
1.13.
Array Operations ........................................................................................................... 16
1.14.
Using Functions............................................................................................................. 17
1.15.
Logical and Relational Operations on Matrices............................................................. 20
1.16.
Sorting Matrices ............................................................................................................ 22
1.17.
Controlling Execution Flow ............................................................................................ 23
1.18.
For Loops ...................................................................................................................... 24
1.19.
While Loops................................................................................................................... 24
1.20.
If Statements ................................................................................................................. 25
1.21.
Nesting .......................................................................................................................... 26
1.22.
Writing Functions........................................................................................................... 27
1.23.
Comments and Help...................................................................................................... 29
1.24.
Data Input and Output ................................................................................................... 29
1.25.
Data Input...................................................................................................................... 30
1.26.
Data Output ................................................................................................................... 31
2.
INTRODUCTION TO VISUAL BASIC ................................................................................... 33
2.1.
Creating Your First Macro ............................................................................................. 33
2.2.
Simple User Defined Functions ..................................................................................... 33
2.2.1.
Where To Put The Function Code ......................................................................................... 34
2.2.2.
User Defined Funtions And Calcuations ................................................................................ 35
Finance is the art of passing currency from hand to hand until it finally disappears. Robert W. Sarnoff
PREFACE
Financial modeling is undoubtedly one of the most difficult courses in advanced finance and the well deserved target for many recent Nobel prizes. I have devoted most of my life to financial modeling, as a banker at Santander, Merrill Lynch, Deutsche Bank and UBS in London, and as a finance professor at ICADE and IE Business School in Madrid. Modeling is not a science but a combination of an art (creativity) and science (technical skills). It takes many books to understand the theoretical foundations of financial modeling. One of my key references has always been Financial Modeling by Simon Benninga. This book is very focused on VBA modeling but it does not cover derivatives at a high level, and besides, it does not use Matlab. I like Simons style a lot, because, not only he teaches things, he does them for real. This book uses Matlab and Visual Basic in order to implement all the models. VBA is excellent but lacks calculation power, and thats when Matlab comes in. I am a big believer in learning by real practise education. Real models are extremely helpful for practisioners that just want to be able to put financial models together for accounting, financial, legal issues, asset management, risk control or any other reasons. Once you see it in the computer, its much easier to be able to cope with the huge density of text books. You do not need to be a rocket scientist to use these models. Last but not least I would like to thank to all my IE Business School students. As Elton John would say this song is for you. Have fun! Antonio Rivela
1. INTRODUCTION TO MATLAB/OCTAVE
MATLAB stands for Matrix Laboratory. According to The Mathworks, its producer, it is a "technical computing environment". We will take the more mundane view that it is a programming language. This section covers much of the language, but by no means all. We aspire to at the least to promote a reasonable proficiency in reading procedures that we will write in the language but choose to address this material to those who wish to use our procedures and write their own programs. Versions of MATLAB are available for almost all major computing platforms. Our material was produced and tested on the version designed for the Microsoft Windows and MAC OS X environment. The vast majority of it should work with other versions, but no guarantees can be offered. Of particular interest are the Student Versions of MATLAB. Prices are generally below $100. These systems include most of the features of the language, but no matrix can have more than 8,192 elements, with either the number of rows or columns limited to 32. For many applications this proves to be of no consequence. At the very least, one can use a student version to experiment with the language. The Student Editions are sold as books with disks enclosed. They are published by Prentice-Hall and can be ordered through bookstores. In addition to the MATLAB system itself, Mathworks offers sets of Toolboxes, containing MATLAB functions for solving a number of important types of problems. Of particular interest to us is the optimization toolbox, which will be discussed in a later section.
C=A+B If both A and B are scalars (1 by 1 matrices), C will be a scalar equal to their sum. If A and B are row vectors of identical length, C will be a row vector of the same length, with each element equal to the sum of the corresponding elements of A and B. Finally, if A and B are, say, {3*4} matrices, so will C, with each element equal to the sum of the corresponding elements of A and B. In short the symbol "+" means "perform a matrix addition". But what if A and B are of incompatible sizes? Not surprisingly, MATLAB will complain with a statement such as:
??? Error using ==> + Matrix dimensions must agree. So the symbol "+" means "perform a matrix addition if you can and let me know if you can't".
C=A+B Creates a variable named C that is also {20*30} and fills it with the appropriate values. If C already existed and was, say {20*15} it would be replaced with the required {20*30} matrix. In MATLAB, unlike some languages, there is no need to "pre-dimension" or "re-dimension" variables. It all happens without any explicit action on the part of the user.
desired). In programming languages there are always tradeoffs. You don't have to declare variables in advance in MATLAB. This avoids a great deal of effort, but it allows nasty, difficult-to-detect errors to creep into your programs.
do_it at the prompt in interactive mode. The statements will then be executed. Even more powerful is the function file; this is also a file with an .m extension, but one that stores a function. For example, assume that the file val_port.m, stored in an appropriate directory, contains a function to produce the value of a portfolio, given a vector of holdings and a vector of prices. In interactive mode, one can then simply type: v = val_port(holdings, prices); MATLAB will realize that it doesn't have a built-in function named val_port and search the relevant directories for a file named val_port.m, then use the function contained in it. 9
Whenever possible, you should try to create "m-files" to do your work, since they can easily be re-used.
C = A + B;
If a matrix is small enough, one can provide initial values by simply typing them in. For example:
a = 3; b = [ 1 2 3]; c = [ 4 ; 5 ; 6]; d = [ 1 2 3 ; 4 5 6]; Here, a is a scalar, b is a {1*3} row vector, c a {3*1} column vector, and d is a {2*3} matrix. Thus, typing "d" produces:
d= 1
3 10
The system for indicating matrix contents is very simple. Values separated by spaces are to be on the same row; those separated by semicolons are on to be on separate rows. All values are enclosed in square brackets.
d = [a ; b] gives: d= 1 4
2 5
3 6
Matrices can easily be "pasted" together in this manner -- a process that is both simple and easily understood by anyone reading a procedure (including its author). Of course, the sizes of the matrices must be compatible. If they are not, MATLAB will tell you.
11
d(1,2) equals 2 d(2,1) equals 4 In every case the first parenthesized expression indicates the row (or rows), while the second expression indicates the column (or columns). If a matrix is, in fact, a vector, a single expression may be given to indicate the desired element, but it is often wise to give both row and column information explicitly, even in such cases. MATLAB's real power comes into play when more than a single element of a matrix is wanted. To indicate "all the rows" use a colon for the first expression. To indicate "all the columns", use a colon for the second expression. Thus, with:
d= 1 4
2 5
3 6
d(1,:) equals 1 2 3 d(:,2) equals 2 5 In fact, you may use any expression in this manner as long as it evaluates to a vector of valid row or column numbers. For example: 12
d(2,[2 3]) equals 5 6 d(2, [3 2]) equals 6 5 Variables may also be used as "subscripts". Thus: if z = [2 3] then d(2,z) equals 5 6 Particularly useful in this context (and others) is the construct that uses a colon to produce a string of consecutive integers. For example: the statement:
1.10.
Text Strings
MATLAB is wonderful with numbers. It deals with text but you can tell that its heart isn't in it. A variable in MATLAB is one of two types: numeric or string. A string matrix is like any other, except the elements in it are interpreted asASCII numbers. Thus the number 32 represents a space, the number 65 a capital A, etc.. To create a string variable, enclose a string of characters in "single" quotation marks (actually, apostrophes), thus: 13
stg = 'This is a string'; Since a string variable is in fact a row vector of numbers, it is possible to create a list of strings by creating a matrix in which each row is a separate string. As with all standard matrices, the rows must be of the same length. Thus: the statement
1.11.
The Mathworks uses the term matrix operation to refer to standard procedures such as matrix multiplication. The term array operation is reserved for element-by-element computations.
14
1.12.
Matrix Operations
Matrix transposition is as easy as adding a prime (apostrophe) to the name of the matrix. Thus: if: x= 123 then: x' = 1 2 3 To add two matrices of the same size, use the plus (+) sign. To subtract one matrix from another of the same size, use a minus (-) sign. If a matrix needs to be "turned around" to conform, use its transpose. Thus, if A is {3*4} and B is {4*3}, the statement:
C=A+B will get you the message: ??? Error using ==> + Matrix dimensions must agree. while: C = A + B' will get you a new matrix. There is one case in which addition or subtraction works when the components are of different sizes. If one is a scalar, it is added to or subtracted from all the elements in the other.
15
Matrix multiplication is indicated by an asterisk (*), commonly regarded in programming languages as a "times sign". With one exception the usual rules apply: the inner dimensions of the two operands must be the same. If they are not, you will be told so. The one allowed exception covers the case in which one of the components is a scalar. In this instance, the scalar value is multiplied by every element in the matrix, resulting in a new matrix of the same size. MATLAB provides two notations for "matrix division" that provide rapid solutions to simultaneous equation or linear regression problems. They are better discussed in the context of such problems.
1.13.
Array Operations
To indicate an array (element-by-element) operation, precede a standard operator with a period (dot). Thus:
18
the "dot product" of x and y. You may divide all the elements in one matrix by the corresponding elements in another, producing a matrix of the same size, as in: C = A ./ B In each case, one of the operands may be a scalar. This proves handy when you wish to raise all the elements in a matrix to a power. For example: if x = 1 2 3 then: 9 16
x.^2 = 1 4
MATLAB array operations include multiplication (.*), division (./) and exponentiation (.^). Array addition and subtraction are not needed (and in fact are not allowed), since they would simply duplicate the operations of matrix addition and subtraction.
1.14.
Using Functions
MATLAB has a number of built-in functions -- many of which are very powerful. Some provide one (matrix) answer; others provide two or more. You may use any function in an expression. If it returns one answer, that answer will be used. The sum function provides an example:
y =sum(x) + 10 will produce: y= 16 Some functions, such as max provide more than one answer. If such a function is included in an expression, only the first answer will be used. For example:
if x = 1
the statement:
17
z= 14 To get all the answers from a function that provides more than one, use a multiple assignment statement in which the variables that are to receive the answers are listed to the left of the equal sign, enclosed in square brackets, and the function is on the right. For example:
if x = 1
y= 4 n= 2 In this case, y is the maximum value in x, and n indicates the position in which it was found. Many of MATLAB's built-in functions, such as sum, min, max, and mean have natural interpretations when applied to a vector. If a matrix is given as an argument to such a function, its procedure is applied separately to each column, and a row vector of results returned. Thus:
if x = 1 4 2 5 then : 18 3 6
sum(x) = 5 7
Some functions provide no answers per se. For example, to plot a vector y against a vector x, simply use the statement:
plot(x,y) which will produce the desired cross-plot. Note that in this case, two arguments (the items in the parentheses after the function name) were provided as inputs to the function. Each function needs a specific number of inputs. However, some have been programmed to react appropriately when fewer are given. For example, to plot y against (1,2,3...), you can use the statement:
plot(y) There are many built-in functions in MATLAB. Among them, the following are particularly useful for Macro-Investment Analysis: ones ones matrix zeros zeros matrix size size of a matrix diag diagonal elements of a matrix inv matrix inverse rand uniformly distributed random numbers randn normally distributed random numbers cumprod cumulative product of elements cumsum cumulative sum of elements max largest component min smallest component sum sum of elements mean average or mean value median median value 19
std standard deviation sort sort in ascending order find find indices of nonzero entries corrcoef correlation coefficients cov covariance matrix Not listed, but of great use, are the many functions that provide plots of data in either two or three dimensions, as well as a number of more specialized functions. However, this list should serve to whet the Analyst's appetite. The full list of functions and information on each one can be obtained via MATLAB's online help system.
1.15.
< : less than <= : less than or equal to > : greater than >= : greater than or equal to == : equal ~= : not equal Note carefully the difference between the double equality and the single equality. Thus A==B should be read "A is equal to B", while A=B should be read "A should be assigned the value of B". The former is a logical relation, the latter an assignment statement. Whenever MATLAB encounters a relational operator, it produces a one if the expression is true and a zero if the expression is false. Thus: the statement:
Relational operators can be used on matrices, as long as they are of the same size. Operations are performed element-by-element, resulting a matrix with ones in positions for which the relation was true and zeros in positions for which the relation was false. Thus: if A = 1 3 2 4 and B = 3 2 1 2
the statement:
C=A>B produces: C= 0 1 1 1
One or both of the operands connected by a relational operator can be a scalar. Thus:
if A = 1 3
2 4 the statement:
C=A>2 produces: C= 0 0 1 1 One may also use logical operators of which there are three: 21
& : and | : or ~ : not Each works with matrices on an element-by-element basis and conforms to the ordinary rules of logic, treating any non-zero element as true and any zero element as false. Relational and logical operators are used frequently with If statements (described below) and scalar variables, as in more mundane programming languages. But the ability to use them with matrices offers major advantages in some Investment applications.
1.16.
Sorting Matrices
To sort a matrix in ascending order, use the sort function. If the argument is a vector, the result will be a new vector with the items in the desired order. If it is a matrix, the result will be a new matrix in which each column will contain the contents of the corresponding column from the old matrix, in ascending order. Note that in the latter case, each column is, in effect, sorted separately. Thus:
if x = 1 3 2
5 2 8 the statement:
To obtain a record of the rows from which each of the sorted elements came, use a multiple assignment to get the second output of the function. For the case above:
Thus the second item in the sorted list in column 1 came from row 3, etc..
1.17.
It is possible to do a great deal in MATLAB by simply executing statements involving matrix expressions, one after the other, However, there are cases in which one simply must substitute some non-sequential order. To facilitate this, MATLAB provides three relatively standard methods for controlling program flow: For Loops, While Loops, and If statements
23
1.18.
For Loops
The most common use of a For Loop arises when a set of statements is to be repeated a fixed number of times, as in:
for j= 1:n ....... end There are fancier ways to use For Loops, but for our purposes, the standard one suffices.
1.19.
While Loops
A While Loop contains statements to be executed as long as a stated condition remains true, as in:
while x > 0.5 ....... end It is, of course, crucial that at some point a statement will be executed that will cause the condition in the While statement to be false. If this is not the case, you have created an infinite loop -- one that will go merrily on until you pull the plug. For readability, it is sometimes useful to create variables for TRUE and FALSE, then use them in a While Loop. For example:
true = 1==1; false = 1==0; ..... done = false; while not done 24
........ end Of course, somewhere in the While loop there should be a statement that will at some point set done equal to true.
1.20.
If Statements
A If Statement provides a method for executing certain statements if a condition is true and other statements (or none) if the condition is false. For example: If x > 0.5 ........ else ....... end In this case, if x is greater than 0.5 the first set of statements will be executed; if not, the second set will be executed. A simpler version omits the "else section", as in: If x > 0.5 ........ end Here, the statements will be executed if (but only if) x exceeds 0.5.
25
1.21.
Nesting
All three of these structures allow nesting, in which one type of structure lies within another. For example:
for j = 1:n for k = 1:n if x(j,k) > 0.5 x(j,k) = 1.5; end end end The indentation is for the reader's benefit, but highly recommended in this and other situations. MATLAB will pair up end statements with preceding for, while, or if statements in a last-come-first-served manner. It is up to the programmer to ensure that this will give the desired results. Indenting can help, but hardly guarantees success on every occasion. While it is tempting for those with experience in traditional programming languages to take the easy way out, using For and While loops for mathematical operations, this temptation should be resisted strenuously. For example, instead of:
port_val = 0; for j = 1:n port_val = port_val + ( holdings(j) * prices(j)); end write: port_val = holdings*prices; The latter is more succinct, far clearer, and will run much faster. MATLAB performs matrix operations at blinding speed, but can be downright glacial at times when loops are to be executed a great many times, since it must do a certain amount of translation of each statement every time it is encountered.
26
1.22.
Writing Functions
The power of MATLAB really comes into play when you add your own functions to enhance the language. Once a function m-file is written, debugged, and placed in an appropriate directory, it is for all practical purposes part of your version of MATLAB. A function file starts with a line declaring the function, its arguments and its outputs. There follow the statements required to produce the outputs from the inputs (arguments). That's it. Here is a simple example:
function y = port_val(holdings,prices) y = holdings*prices; Of course, this will only work if the holdings and prices vectors or matrices are compatible for matrix multiplication. A more complex version could examine the sizes of these two matrices, then use transposes, etc. as required. It is important to note that the argument and output names used in a function file are strictly local variables that exist only within the function itself. Thus in a program, one could write the statement:
v = port_val(h,p); The first matrix in the argument list in this calling statement (here, h) would be assigned to the first argument in the function (here, holdings) while the second matrix in the calling statement (p) would be assigned to the second matrix in the function (prices). There is no need for the names to be the same in any respect. Moreover, the function cannot change the original arguments in any way. It can only return information via its output.
27
This function returns only one output, called y internally. However, the resultant matrix will be substituted for the entire argument "call" in any expression. If a function is to return two or more arguments, simply assign them names in the declaration line, as in:
function [total_val, avg_val] = port_val(holdings,prices) total_val = holdings*prices; avg_val = total_val/size(holdings,2); This can still be used as in the earlier case if only the total value is desired. To get both the total value and the average value per position, a program could use a statement such as: [tval aval] = port_val( h,p); Note that as with inputs, the correspondence between outputs in the calling statement and the function itself is strictly by order. When the function has finished its work, its output values are assigned to the variables in the calling statement. Variables other than inputs and arguments may be included in functions, as needed. They are strictly local to the function and have no existence outside it. Indeed, a variable in a function may have the same name as one in another place; the two will coexist with neither bothering the other. While MATLAB provides for the use of "global variables", their use is widely discouraged and will not be treated here.
28
1.23.
It is an excellent idea to include comments throughout any m-file. To do so, use the percent (%) sign. Everything after it up to the end of the line will be ignored by MATLAB. The first several lines after each function header should provide a brief description of the function and its use. Once the function has been placed in an appropriate directory, a user need only type help followed by the function name to be shown all the initial comment lines (up to the first non-comment or totally blank line). Thus if there is a function named port_val, the user can get this information by typing:
help port_val To provide even more assistance, create a script file with nothing but comment lines, each giving the name and a brief description of all your functions and scripts. If this were named mia_fun, the user could simply type:
help mia_fun to get a list of your functions, then type help function name to get more details on any specific function.
1.24.
There are many ways to get information into and out of the MATLAB environment. We will cover only the simpler ones here.
29
1.25.
Data Input
The most straightforward way to get information into MATLAB is to type it in "command mode". For example:
prices = [ 12.50 37.875 12.25]; assets = ['cash ';'bonds ' ; 'stocks']; MATLAB even makes it easy to enter matrices in a more normal form by treating carriage returns as semicolons within brackets. Thus:
holdings = [ 100 200 300 400 500 600 ] will create a {3*2} matrix, as desired. A second way to get data into MATLAB is to create a script file with the required statements, such as the one above. This can be done with any text processor. Large matrices of data can even be "cut out" of databases, spreadsheets, etc. then edited to include the desired variable names, square brackets and the like. Once the file or files are saved with .m names they only have to be invoked to bring the data into MATLAB. Next up the chain of complexity is the use of a flat file which stores data for a matrix. Such a file should have numeric ascii text characters, with each element in a row separated from its neighbor with a space and each row on a separate line. Say, for example, that you have stored the elements of a matrix in a file named test.txt in a directory on the MATLAB path. Then the statement: load test.txt will create a matrix named test containing the data. 30
1.26.
Data Output
A simple way to output data is to display a matrix. This can be accomplished by either giving its name (without a semicolon) in interactive mode. Alternatively you can use the disp function, which shows values without the variable name, as in: disp(test); For prettier output, MATLAB has various functions for creating strings from numbers, formatting data, etc.. Function pmat can produce small tables with string identifiers on the borders. If you want to save almost everything that appears on your screen, issue the command:
diary filename where filename represents the name of a new file that will receive the subsequent output. When you are through, issue the command:
diary off Later, at your leisure, you may use a text editor to extract data, commands, etc. to data files, script or function files, and so on. There are, of course, other alternatives. If you are in an environment (such as a Windows system) that allows material to be copied from one program and pasted into another, this may suffice. To create a flat file containing the data from a matrix use the -ascii version of the save command. For example: 31
save newdata.txt test ascii will save the matrix named test in the file named newdata.txt. Finally, you may save all or part of the material from a MATLAB session in MATLAB's own mat file format. To save all the variables in a file named temp.mat, issue the command:
save temp At some later session you may load all this information by simply issuing the command:
load temp To save only one or more matrices in this manner, list their names after the file name. Thus:
save temp prices holdings portval would save only these three matrices in file temp.mat. Subsequent use of the command:
load temp would restore the three named matrices, with their values intact. There are more sophisticated ways to move information into and out of MATLAB, but they can be left to others.
32
1. Open Visual Basic Editor by go to Tools...Macro...Visual Basic Editor or just simply press the [Alt] and [F11] keys at the same time.
2. In the Insert menu on top of the Visual Basic Editor, select Module to open the Module window (code window). 3. In the Module window, type the following:
4. Click the Run button,, press [F5], or go to Run..Run Sub/UserForm to run the program 5. The message box pops up with the "Hello World!" greeting.
change anything in Excel. This was fixed with Excel 2002.The following is an example of a simple UDF that calculates the area of a rectangle: Function RectangleArea(Height As Double, Width As Double) As Double RectangleArea = Height * Width End Function This function takes as inputs two Double type variables, Height and Width, and returns a Double as its result. Once you have defined the UDF in a code module, you can call it from a worksheet cell with a formula like:=RectangleArea(A1,B1)where A1 and B1 contain the Height and Width of the rectangle. Because functions take inputs and return a value, they are not displayed in the list of procedures in the Macros dialog.
A module can contain any number functions, so you can put many functions into a single code module. You can change the name of a module from Module1 to something more meaningful by pressing the F4 key to display the Properties window and changing the Name property to whatever you want. You can call a function from the same workbook by using just the function name. For example:=RectangleArea(12,34)It is possible, but strongly recommended against, to have two functions with the same name is two separate code modules within the same workbook. You would call them using the module name from cells with formulas like: =Module1.MyFunction(123)=Module2.MyFunction(123)
Doing this will lead only to confusion, so just because it is possible doesn't mean you should do it. Don't do it. Do not give the same name to both a module and a function (regardless of whether that module contains that function). Doing so will cause an untrappable error. You can call a UDF that is contained in another (open) workbook by using the workbook name in the formula. 34
For example, ='MyBook.xls'!RectangleArea(A1,A2) will call the function RectangleArea defined in the workbook MyBook.xls. If a function is defined in an Add-In (either an XLA or an Automation Add-In; The function name alone is sufficient for calling a function in an Add-In.
group of objects of the same class. The most used Excel objects in VBA programming are Workbook, Worksheet, Sheet, and Range. Workbooks is a collection of all Workbook objects. Worksheets is a collection of Worksheet objects. The Workbook object represents a workbook, the Worksheet object represents a worksheet, the Sheet object represents a worksheet or chartsheet, and the Range object represents a range of cells. The following figure shows all the objects mentioned. The workbook (Excel file) is currently Book3.xls. The current worksheet is Sheet1 as the Sheet Tab indicated. Two ranges are selected, range B2 and B7:B11.
Sheets is a collection of worksheets and chart sheets (if present). A sheet can be indexed just like a worksheet. Sheets(1) is the first sheet in the workbook. To refer sheets (or other objects) with the same name, you have to qualify the object. For example: Workbooks("Book1").Worksheets("Sheet1") Workbooks("Book2").Worksheets("Sheet1") If the object is not qualified, the active or the current object (for example workbook or worksheet) is used. The sheet tab on the buttom the spreadsheet (worksheet) shows which sheet is active. As the figure below shows, the active sheet is "Sheet1" (show in bold font and white background). 36
* You can change the color of the sheet tabs by right click the tab, choose Tab Color, then select the color for the tab. The sub routine below shows the name of each sheet in the current opened workbook. You can use For Each...Next loop to loop throgh the Worksheets collection. Sub ShowWorkSheets() Dim mySheet As Worksheet For Each mySheet In Worksheets MsgBox mySheet.Name Next mySheet End Sub
The following three statements are interchangable: ActiveSheet.Range.Cells(1,1) Range.Cells(1,1) Cells(1,1) The following returns the same outcome: Range("A1") = 123 and Cells(1,1) = 123
The following puts "XYZ" on Cells(1,12) or Range("L1") assume cell A1 is the current cell: Cells(12) = "XYZ" The following puts "XYZ" on cell C3: Range("B1:F5").cells(12) = "ZYZ" * The small gray number on each of the cells is just for reference purpose only. They are used to show how the cells are indexed within the range. Here is a sub routine that prints the corresponding row and column index from A1 to E5. Sub CellsExample() For i = 1 To 5 For j = 1 To 5 Cells(i, j) = "Row " & i & " Col " & j Next j Next i End Sub Range object has an Offset property that can be very handy when one wants to move the active cell around. The following examples demostrate how the Offset property can be implemented (assume the current cell before the move is E5): ActiveCell.Offset(1,0) = 1 ActiveCell.Offset(0,1) = 1 E5 (on F5) ActiveCell.Offset(0,-3) = 1 E5 (on B5) Place a "1" one row under E5 (on E6) Place a "1" one column to the right of Place a "1" three columns to the left of
38
Here are examples on how to set and to get a Range property value: The following sets the value of range A1 or Cells(1,1) as "2005". It actually prints "2005" on A1. Range("A1").Value = 2005 The following gets the value from range A1 or Cells(1,1). X = Range("A1").Value Method can be used with or without argument(s). The following two examples demostrate this behavior. Methods That Take No Arguments: Worksheets("Sheet").Column("A:B").AutoFit Methods That Take Arguments: Worksheets("Sheet1").Range("A1:A10").Sort _ Worksheets("Sheet1").Range("A1") Worksheets("Sheet1").Range("A1") is the Key (or column) to sort by.
39
Procedures in Visual Basic can have either private or public scope. A procedure with private scope is only accessible to the other procedures in the same module; a procedure with public scope is accessible to all procedures in in every module in the workbook in which the procedure is declared, and in all workbooks that contain a reference to that workbook. By default, procedures has public scope. Here are examples of defining the scope for procedure. Public Sub ShowTime() Range("C1") = Now() End Sub Private Sub ShowTime() Range("C1") = Now() End Sub
41
42
number. Changes made to one element of an array don't affect the other elements.
Before signing values to an array, the array needs to be created. You can declare the array by using the Dim statement. For example, to declare a one-dimensional array with 5 elements, type the following: Dim Arr(4) The elements index of the array starts from 0 unless Option Base 1 is specified in the public area (area outside of the sub procedure). If Option Base 1 is specified, the index will start from 1. The following example assigns values to the array and displays all values in a message box : Option Base 1 Sub assignArray( ) Dim Arr(5) Arr(1) = Jan Arr(2) = Feb Arr(3) = Mar Arr(4) = Apr Arr(5) = May Msgbox Arr(1) & "-" & Arr(2) & "-" & Arr(3) & "-" & Arr(4) & "-" & Arr(5) End Sub
* The number inside the array, i.e. Arr(1), is the index. One (1) is the index of the first element in the array.
44
Arr(3) = Mar Arr(4) = Apr Arr(5) = May Redim Arr(6) Arr(6) = Jun Msgbox Arr(1) & "-" & Arr(2) & "-" & Arr(3) & "-" & Arr(4) & "-" & Arr(5) & "-" & Arr(6) End Sub By replace the Redim Arr(6) with Redim Preserve Arr(6), all values will remain. For example: Option Base 1 Sub assignArray( ) Redim Arr(5) Arr(1) = Jan Arr(2) = Feb Arr(3) = Mar Arr(4) = Apr Arr(5) = May Redim Preserve Arr(6) Arr(6) = Jun Msgbox Arr(1) & "-" & Arr(2) & "-" & Arr(3) & "-" & Arr(4) & "-" & Arr(5) & "-" & Arr(6) End Sub
Dim Arr(2,2) Then we assign the values into the array. We treat the first dimension as the year and the second dimension as the product sale: arr(1,1) = 1000 arr(1,2) = 1200 arr(2,1) = 1500 arr(2,2) = 2000 We now display the values of the array with a message box: Msgbox "Sale of CD in 2003 is " & arr(1,1) & vbCrLf & "Sale of CD in 2004 is " _& arr(2,1) & vbCrLf & "Sale of DVD in 2003 is " & arr(1,2) & vbCrLf _ & "Sale of DVD in 2004 is " & arr(2,2) The complete precedure is as followed: Option Base 1 Sub multDimArray( ) Dim Arr(2,2) arr(1,1) = 1000 arr(1,2) = 1200 arr(2,1) = 1500 arr(2,2) = 2000 Msgbox "Sale of CD in 2003 is " & arr(1,1) & vbCrLf & "Sale of CD in 2004 is " _& arr(2,1) & vbCrLf & "Sale of DVD in 2003 is " & arr(1,2) & vbCrLf _& "Sale of DVD in 2004 is " & arr(2,2) End Sub
* vbCrLf stands for VB Carriage Return Line Feed. It puts a return and a new line as shown in the message box above. The underscore "_" on the back of the first line of the message box means "continue to the next line"
In our two-dimensional array example above, there are two upper bound figures - both are 2. UBound returns the following values for an array with these dimensions*: Dim A(1 To 100, 0 To 3, -3 To 4) Statement UBound(A, 1) UBound(A, 2) UBound(A, 3) Return Value 100 3 4
* Example taken from Excel VBA Help section. The UBound function is used with the LBound function to determine the size of an array. Use the LBound function to find the lower limit of an array dimension. Statement LBound(A, 1) LBound(A, 2) LBound(A, 3) Return Value 1 0 -3
To get the size of an array, use the following formula: UBound(Arr) - LBound(Arr) + 1 For example: Ubound(A,1) - LBound(A,1) + 1 = 100 - 1 + 1 = 100 Ubound(A,2) - LBound(A,2) + 1 =3-0+1 =4 Ubound(A,3) - LBound(A,3) + 1 = 4 - (-3) + 1 =8
errors. If you enter it into a smaller range, you will not get all the values created by LINEST. To mandate the size of the returned array, simply declare the array to that size and setting the result of the function to that array. For example, Function Test() As Variant Dim V() As Variant Dim N As Long Dim R As Long Dim C As Long ReDim V(1 To 3, 1 To 4) For R = 1 To 3 For C = 1 To 4 N=N+1 V(R, C) = N Next C Next R Test = V End Function This function simply returns an array with 3 rows and 4 columns that contains the integers from 1 to 12. Returning such a fixed-size array can be useful if the number of results does not vary with the number and/or values of the inputs to the function. However, this is usually not the case. In the majority of circumstances, if your UDF is going to return an array, that array will vary in size and the size will depend on any one or more of three things: the size of the range into which the UDF was entered, the number of elements passed into the function, and, of course, the nature and function of the UDF itself. The Application.Caller object, when used in a UDF called from a worksheet range, is a Range reference to the range from which your UDF was called.
single-dimensional arrays and only when the UDF is being called from a worksheet range. Therefore, you should first test Application.Caller with IsObject and then test Application.Caller.Rows.Count and Application.Caller.Columns.Count to test if it is being called from a row or column vector. For example, Function Test(NN As Long) Dim Result() As Long Dim N As Long ReDim Result(1 To NN) For N = 1 To NN Result(N) = N Next N If Application.Caller.Rows.Count > 1 Then Test = Application.Transpose(Result) Else Test = Result End If End Function You can, of course, forego this and return the array as-is and leave it up to the user to use the TRANSPOSE function to properly orient the array.
50
51
52
In this example, i is the counter variable from 1 to 10. The looping process will send value to the first column of the active sheet and print i (which is 1 to 10) to row 1 to 10 of that column. Note that the counter variable, by default, increases by an increment of 1.
For example: For i = 10 to 1 Step -2 Cells(i, 1) = i Next i This looping process will print values with an increment of -2 starts from 10 on row 10, 8, 6, 4 and 2 on column one.
Cells(i, 1) = i i=i+1 Loop This looping process yields the same result as in the For ... Next structures example.