Anda di halaman 1dari 55

INTRODUCTION TO FINANCIAL PROGRAMMING

Antonio Rivela
first edition

USES MATLAB, EXCEL AND VISUAL BASIC

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

2.3. Objects and Collections................................................................................................. 35


2.3.1. Workbook and Worksheet Object .......................................................................................... 36 2.3.2. Range Object and Cells Property........................................................................................... 37

2.4. Methods and Properties ................................................................................................ 39

2.4.1. Assigning Object Variables and Using Named Argument...................................................... 40

2.5. Modules and Procedures .............................................................................................. 40


2.5.1. Modules and Procedures and Their Scope............................................................................ 40 2.5.2. Calling Sub Procedures and Function Procedures ................................................................ 42 2.5.3. Passing Argument by Reference or by Value ........................................................................ 43

2.6. Creating and Managing Arrays...................................................................................... 43


2.6.1. Declaring an Array With Dim Statement ................................................................................ 44 2.6.2. Resize an Array With Redim Statement................................................................................. 45 2.6.3. Manage Dynamic Array ......................................................................................................... 45 2.6.4. Create Multi-Dimensional Array ............................................................................................. 46 2.6.5. Find The Size of an Array ..................................................................................................... 47 2.6.6. Choosing The Right Return Array Size .................................................................................. 48 2.6.7. Orienting An Array.................................................................................................................. 49

2.7. Decision Structures - IF and Select Case ..................................................................... 51


2.7.1. IF ... Then Statement ............................................................................................................. 51 2.7.2. IF ... Then ... Else................................................................................................................... 51 2.7.3. IF ... Then ... ElseIf................................................................................................................. 52 2.7.4. Select Case............................................................................................................................ 52

2.8. Loop Structures ............................................................................................................. 53


2.8.1. For ... Next ............................................................................................................................. 53 2.8.2. For ... Next Loop With Step.................................................................................................... 53 2.8.3. Do While ... Loop.................................................................................................................... 54 2.8.4. Do Until ... Loop ..................................................................................................................... 54 2.8.5. Do ... Loop While.................................................................................................................... 55 2.8.6. Do ... Loop Until ..................................................................................................................... 55

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.

1.1. Matrices as Fundamental Objects


MATLAB is one of a few languages in which each variable is a matrix (broadly construed) and "knows" how big it is. Moreover, the fundamental operators (e.g. addition, multiplication) are programmed to deal with matrices when required. And the MATLAB environment handles much of the bothersome housekeeping that makes all this possible. Since so many of the procedures required for Macro-Investment Analysis involve matrices, MATLAB proves to be an extremely efficient language for both communication and implementation.

1.2. Matrix Operations


Consider the following MATLAB expression:

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".

1.3. Assignment Statements


MATLAB uses a pattern common in many programming languages for assigning the value of an expression to a variable. The variable name is placed on the left of an equal sign and the expression on the right. The expression is evaluated and the result assigned to the variable name. In MATLAB, there is no need to declare a variable before assigning a value to it. If a variable has previously been assigned a value, the new value overrides the predecessor. This may sound obvious, but consider that the term "value" now includes information concerning the size of matrix as well as its contents. Thus if A and B are of size {20*30} the statement:

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.

1.4. Case Sensitivity


MATLAB variable names are normally case-sensitive. Thus variable C is different from variable c. A variable name can have up to 19 characters, including letters, numbers and underscores. While it is tempting to use names such as FundReturns it is safer to choose instead fund_returns or to use the convention from the C language of capitalizing only second and subsequent words, as in fundReturns. In any event, a\Adopt a simple set of naming conventions so that you won't write one version of a name in one place and another later. If you do so, you may get lucky (e.g. the system will complain that you have asked for the value of an undefined variable) or you may not (e.g. you will assign the new value to a newly-created variable instead of the old one 8

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.

1.5. Immediate and Deferred Execution


When MATLAB is invoked, the user is presented with an interactive environment. Enter a statement, press the carriage return ("ENTER") and the statement is immediately executed. Given the power that can be packed into one MATLAB statement, this is no small accomplishment. However, for many purposes it is desirable to store a set of MATLAB statements for use when needed. The simplest form of this approach is the creation of a script file: a set of commands in a file with a name ending in .m (e.g. do_it.m). Once such a file exists and is stored on disk in a directory that MATLAB knows about (i.e. one on the "MATLAB path"), the user can simply type:

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.

1.6. Showing Values


If at any time you wish to see the contents of a variable, just type its name. MATLAB will do its best, although the result may take some space if the variable is a large matrix. MATLAB likes to do this and will tell you what it has produced after an assignment statement unless you request otherwise. Thus if you type: C=A+B MATLAB will show you the value of C. This may be a bit daunting if C is, say, a 20 by 30 matrix. To surpress this, put a semicolon at the end of any assignment statement. For example:

C = A + B;

1.7. Initializing Matrices

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.

1.8. Making Matrices from Matrices


The general scheme for initializing matrices can be extended to include matrices as components. For example:

a = [1 2 3]; b = [4 5 6]; c = [a b]; gives: c= 1 2 3 While: 4 5 6

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

1.9. Using Portions of Matrices


Frequently one wishes to reference only a portion of a matrix. MATLAB provides simple and powerful ways to do so. To reference a part of a matrix, give the matrix name followed by parentheses with expressions indicating the portion desired. The simplest case arises when only one element is wanted. For example, using d in the previous section:

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:

x = 3:5 produces x= 3 Thus: d(1, 1:2) equals 2 4 5

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

x = ['ab' ; 'cd'] produces: x= ab cd while x = ['ab' 'cd'] produces: x= abcd as always.

1.11.

Matrix and Array Operations

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:

if x = 1 2 and y = 4 5 then: x.*y = 4 10 3 6

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:

if x = 1 2 3 then the statement:

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 = 10 + max(x) will produce:

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

the statement: [y n] = max(x) will produce:

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.

Logical and Relational Operations on Matrices

MATLAB offers six relational operators:

< : 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:

x = 1 < 3 produces: x=1, while x = 1 > 3 produces: x=0 20

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:

y=sort(x) will produce: y= 1 2 3 2 5 8 22

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:

the statement: [y r] = sort(x) would produce y as before and r= 1 3 2 2 1 3

Thus the second item in the sorted list in column 1 came from row 3, etc..

1.17.

Controlling Execution Flow

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.

Comments and Help

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.

Data Input and Output

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

2. INTRODUCTION TO VISUAL BASIC


2.1. Creating Your First Macro
In this section, we will show you how to create your first macro (VBA program). We will use the world classic "Hello World!" example. To create the example, please follow the following steps:

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:

Sub showMessage() MsgBox "Hello World!" End Sub

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.

Now you are a VBA programmer!

2.2. Simple User Defined Functions


A User Defined Function (or UDF) is a Function procedure that typically (but not necessarily) accepts some inputs and returns a result. A UDF can only return a value to the cell(s) whence it was called -- it must not modify the contents or formatting of any cell and must not modify the operating environment of Excel. If you attempt to change anything, the function will terminate immediately and return a #VALUE error to the calling cell. In Excel 97 and 2000, a UDF cannot use the Find method of a Range object, even though that method does not 33

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.

2.2.1. Where To Put The Function Code


The code for a UDF should be placed in a standard code module, not one of the Sheet modules and not in the ThisWorkbook module. In the VBA editor, go to the Insert menu and choose Module. This will insert a new code module into the project.

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.

2.2.2. User Defined Funtions And Calcuations


As a general rule, you should pass into the function all the values it needs to properly calculate the result. That means that your UDF should not make explicit refences to other cells. If you reference other cells directly from within the function, Excel may not recalculate the function when that cell is changed. For example, a poorly written UDF is as follows: Public Function BadRectangleArea(Height As Double) As Double BadRectangleArea = Height * Range("A1").Value End Function In this function, the Width is assumed to be in cell A1. The problem here is that Excel doesn't know that this function depends on cell A1 and therefore will not recalculate the formula when A1 is changed. Thus, the cell calling the function call will not contain the correct result when cell A1 is changed. You can force Excel to recalculate a UDF whenever any calculation is made by adding the lineApplication.Volatile Trueas the first line in the function. For example, Function BadRectangleArea(Height As Double) As Double Application.Volatile True BadRectangleArea = Height * Range("A1").Value End Function This has the drawback, however, that the function is recalculated even if it doesn't need to be recalculated, which can cause a performance problem. In general, you shouldn't use Application.Volatile but instead design your UDF to accept as inputs everything it needs to properly caclulate the result.

2.3. Objects and Collections


Objects are the fundamental building blocks of Visual Basic. An object is a special type of variable that contains both data and codes. A collection is a 35

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.

2.3.1. Workbook and Worksheet Object


A workbook is the same as an Excel file. The Workbook collection contains all the workbooks that are currently opened. Inside of a workbook contains at least one worksheet. In VBA, a worksheet can be referenced as followed: Worksheets("Sheet1") Worksheets("Sheet1") is the worksheet that named "Sheet1." Another way to refer to a worksheet is to use number index like the following: Worksheets(1) The above refers to the first worksheet in the collection. * Note that Worksheets(1) Worksheets("Sheet1"). is not necessary the same sheet as

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

2.3.2. Range Object and Cells Property


Range represents a cell, a row, a column, a selection of cells containing one or more contiguous blocks of cells, or a 3-D range. We will show you some examples on how Range object can be used. The following example places text "AB" in range A1:B5, on Sheet2. Worksheets("Sheet2").Range("A1:B5") = "AB" Note that, Worksheets.Range("A1", "B5") = "AB" will yield the same result as the above example. The following place "AAA" on cell A1, A3, and A5 on Sheet2. Worksheets("Sheet2").Range("A1, A3, A5") = "AAA" Range object has a Cells property. This property is used in every VBA projects on this website (very important). The Cells property takes one or two indexes as its parameters. For example, Cells(index) or Cells(row, column) where row is the row index and column is the column index. 37

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

2.4. Methods and Properties


Each object contains its own methods and properties. A Property represents a built-in or user-defined characteristic of the object. A method is an action that you perform with an object. Below are examples of a method and a property for the Workbook Object: Workbooks.Close Close method close the active workbook Workbooks.Count Count property returns the number of workbooks that are currently opened Some objects have default properties. For example, Range's default property is Value. The following yields the same outcome. Range("A1") = 1 and Range("A1").Value = 1

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

2.4.1. Assigning Object Variables and Using Named Argument


Sometime a method takes more than one argument. For example, the Open method for the Workbook object, takes 12 arguments. To open a workbook with password protection, you would need to write the following code: Workbooks.Open "Book1.xls", , , ,"pswd" Since this method takes so many arguments, it is easy to misplace the password argument. To overcome this potential problem, one can use named arguments like the following example: Workbook.Open fileName:="Book1.xls", password:="pswd" You can also assign an object to an object variable using the Set Statement. For example: Dim myRange as Range Set myRange = Range("A1:A10")

2.5. Modules and Procedures


2.5.1. Modules and Procedures and Their Scope
A module is a container for procedures as shown in our prior examples. A procedure is a unit of code enclosed either between the Sub and End Sub statement or between the Function and End Function statements. The following sub procedure (or sub routine) print the current date and time on cell C1: Sub ShowTime() Range("C1") = Now() End Sub The following function sum up two numbers: Function sumNo(x, y) sumNo = x + y End Function 40

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

2.5.2. Calling Sub Procedures and Function Procedures


There are two ways to call a sub procedure. The following example shows how a sub procedure can be called by other sub procedures. Sub z(a) MsgBox a End Sub Sub x() Call z("ABC") End Sub Sub y() z "ABC" End Sub Sub z procedure takes an argument (a) and display the argument value ("ABC") in a message box. Running either Sub x or Sub y will yield the same result. The following example calls a function procedure from a sub procedure. Sub ShowSum() msgbox sumNo(3,5) End Sub Function sumNo(x, y) sumNo = x + y End Function The ShowSum sub procedure calls the sumNo function and returns an "8" in a message box. If there are procedures with duplicate names in different modules, you must need to include a module qualifier before the procedure name when calling the procedure. For example: Module1.ShowSum

42

2.5.3. Passing Argument by Reference or by Value


If you pass an argument by reference when calling a procedure, the procedure access to the actual variable in memory. As a result, the variable's value can be changed by the procedure. Passing by reference is the default in VBA. If you do not explicitly specify to pass an argurment by value, VBA will pass it by reference. The following two statements yield the same outcome. Sub AddNo(ByRef x as integer) Sub AddNo(x as integer) Here is an example to show the by reference behavior. The sub procedure, TestPassing 1 calls AddNo1 by reference and display "60" (50 + 10) on the message box. Sub TestPassing1() Dim y As Integer y = 50 AddNo1 y MsgBox y End Sub Sub AddNo1(ByRef x As Integer) x = x + 10 End Sub The following example shows the by value behavior. The sub procedure, TestPassing 2 calls AddNo2 by value and display "50" on the message box. Sub TestPassing2() Dim y As Integer y = 50 AddNo2 y MsgBox y End Sub Sub AddNo2(ByVal x As Integer) x = x + 10 End Sub

2.6. Creating and Managing Arrays


An array is a set of sequentially indexed elements having the same intrinsic data type. Each element of an array has a unique identifying index 43

number. Changes made to one element of an array don't affect the other elements.

2.6.1. Declaring an Array With Dim Statement

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

2.6.2. Resize an Array With Redim Statement


The ReDim statement is used to size or resize a dynamic array that has already been formally declared. For example, if you have already declared an array with an element value of 5 and decided to change the number of the element to 6, you can do the following to resize the array: Redim Arr(6) We incorporate it into our last example: Option Base 1 Sub assignArray( ) 'Dim Arr(5) Redim Arr(6) Arr(1) = Jan Arr(2) = Feb Arr(3) = Mar Arr(4) = Apr Arr(5) = May Arr(6) = Jun Msgbox Arr(1) & "-" & Arr(2) & "-" & Arr(3) & "-" & Arr(4) & "-" & Arr(5) End Sub Note that the Dim Arr(5) statement is commoned out, because leaving this original statement in the sub will causing a compile error.

2.6.3. Manage Dynamic Array


A word of caution in using the Redim Statement to resize an array resize the array can erase the elements in it. In the following example, all the values assigned prior to resize the array are erased. Only the value assigned to the array after resize remains. Option Base 1 Sub assignArray( ) Redim Arr(5) Arr(1) = Jan Arr(2) = Feb 45

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

2.6.4. Create Multi-Dimensional Array


An array can also store multiple dimensional data. To simplify our tutorial, example on a two-dimensional array is used. Assume you have data of a local store's yearly sale in the following table and you want to store the data in a two-dimensional array: CD Sale DVD Sale Year 2003 1,000 1,200 Year 2004 1,500 2,000

First we create the array as follow: 46

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"

2.6.5. Find The Size of an Array


The largest available subscript for the indicated dimension of an array can be obtained by using the Ubound function. In our one-dimensional array example, Ubound(arr) is 5. 47

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

2.6.6. Choosing The Right Return Array Size


At its simplest, the size of the returned array can be mandated by the function and require that the user use an array that size in order to get all the results. The Excel function LINEST function works this way. You must array-enter that function into a range of cells that is 5 rows tall and 2 columns wide. If you enter it into a larger range, Excel fills out the unused elements of the range with #N/A 48

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.

2.6.7. Orienting An Array


If your UDF creates a 1-dimensional array as its result, it can orient the array as either a row vector or a column vector so that is will be properly displayed in the worksheet cells without requiring the user to wrap your UDF result in a TRANSPOSE function. If the function was called from a row vector of cells (e.g., A1:E1), it does not need to be transposed. If the function was called from a column vector of cells (e.g., A1:A5), the array needs to be transposed. The code below looks at Application.Caller.Rows.Count and if this is greater than 1, it tranposes the array before returning it to the caller. Note that this should be done only with 49

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

2.7. Decision Structures - IF and Select Case


2.7.1. IF ... Then Statement
The IF ... Then is a single condition and run a single statement or a block of statement. Example, the following statement set variable Status to "Adult" if the statement is true: If Age >= 18 Then Status = "Adult" You can also use multiple-line block in the If statement as followed: If Ago >= 18 Then Status = "Adult" Vote = "Yes" End If Note that in the multiple-line block case, End If statement is needed, where the single-line case does not.

2.7.2. IF ... Then ... Else


The If ... Then ... Else statement is used to define two blocks of conditions - true and false. Example: If Age >=22 Then Drink = "Yes" Else Drink = "No" End If Again, note that End If statement is needed in this case as well since there is more than one block of statements.

51

2.7.3. IF ... Then ... ElseIf


The IF ... Then ... ElseIf is used to test additional conditions without using new If ... Then statements. For Example: If Age >= 18 and Age < 22 Then Msgbox "You can vote" ElseIf Age >=22 and Age < 62 Then Msgbox "You can drink and vote" ElseIf Age >=62 Then Msgbox "You are eligible to apply for Social Security Benefit" Else Msgbox "You cannot drink or vote" End If Note that the last condition under Else is, implicitly, Age < 18.

2.7.4. Select Case


Select Case statement is an alternative to the ElseIf statement. This method is more efficient and readable in coding the the If ... Then ... ElseIf statment. Example: Select Case Grade Case Is >= 90 LetterGrade = "A" Case Is >= 80 LetterGrade = "B" Case Is >= 70 LetterGrade = "C" Case Is >= 60 LetterGrade = "D" Case Else LetterGrade = "Sorry" End Select

52

2.8. Loop Structures


2.8.1. For ... Next
Use For ... Next loop if the number of loops is already defined and known. A For ... Next loop uses a counter variable that increases or decreases in value during each iteration of the loop. This loop structure is being used the most for our examples on this site. Here is an example of the For ... Next loop: For i = 1 to 10 Cells(i, 1) = i Next i

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.

2.8.2. For ... Next Loop With Step


You can use the Step Keyword to sepcify a different increment for the counter variable. For example: For i = 1 to 10 Step 2 Cells(i, 1) = i Next i This looping process will print values with an increment of 2 on row 1, 3, 5, 7 and 9 on column one. You can also have decrement in the loop by assign a negative value afte the Step keyword. 53

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.

2.8.3. Do While ... Loop


You can use the Do While ... Loop to test a condition at the start of the loop. It will run the loop as long as the condition is ture and stops when the condition becomes false. For Example: i=1 Do While i =< 10 Cells(i, 1) = i i=i+1 Loop This looping process yields the same result as in the For ... Next structures example. One thing to be caution is that sometimes the loop might be a infinite loop. And it happens when the condition never beomes false. In such case, you can stop the loop by press [ESC] or [CTRL] + [BREAK].

2.8.4. Do Until ... Loop


You can test the condition at the beginning of the loop and then run the loop until the test condition becomes true. Example: i=1 Do Until i = 11 54

Cells(i, 1) = i i=i+1 Loop This looping process yields the same result as in the For ... Next structures example.

2.8.5. Do ... Loop While


When you want to make sure that the loop will run at least once, you can put the test at the end of loop. The loop will stop when the condition becomes false. (compare this loop structure to the Do ... While Loop.) For Example: i=1 Do Cells(i, 1) = i i =i+1 Loop While i < 11 This looping process yields the same result as in the For ... Next structures example.

2.8.6. Do ... Loop Until


This loop structure, like the Do ... Loop While, makes sure that the loop will run at least once, you can put the test at the end of loop. The loop will stop when the condition becomes true. (compare this loop structure to the Do ... Until Loop.) For Example: i=1 Do Cells(i, 1) = i i =i+1 Loop Until i = 11 This looping process yields the same result as in the For ... Next structures example. 55