Introduduction to Financial Programming

Embed Size (px)

Citation preview

  • 7/30/2019 Introduduction to Financial Programming

    1/55

    INTRODUCTION TO

    FINANCIAL PROGRAMMING

    Antonio Rivela

    first edition

    USES MATLAB, EXCELAND VISUAL BASIC

  • 7/30/2019 Introduduction to Financial Programming

    2/55

    2

    INDEX

    1. INTRODUCTION TO MATLAB/OCTAVE ............................................................................... 61.1. Matrices as Fundamental Objects................................................................................... 71.2. Matrix Operations ............................................................................................................ 71.3. Assignment Statements .................................................................................................. 81.4. Case Sensitivity ............................................................................................................... 81.5. Immediate and Deferred Execution................................................................................. 91.6. Showing Values............................................................................................................. 101.7. Initializing Matrices ........................................................................................................ 101.8. Making Matrices from Matrices ..................................................................................... 111.9. Using Portions of Matrices ............................................................................................ 121.10. Text Strings ................................................................................................................... 131.11. Matrix and Array Operations ......................................................................................... 141.12. Matrix Operations .......................................................................................................... 151.13.Array Operations ........................................................................................................... 161.14. Using Functions............................................................................................................. 171.15. Logical and Relational Operations on Matrices............................................................. 201.16. Sorting Matrices ............................................................................................................ 221.17. Controlling Execution Flow............................................................................................ 231.18.

    For Loops ...................................................................................................................... 24

    1.19. While Loops................................................................................................................... 241.20. If Statements ................................................................................................................. 251.21. Nesting .......................................................................................................................... 261.22. Writing Functions........................................................................................................... 271.23. Comments and Help...................................................................................................... 291.24. Data Input and Output ................................................................................................... 291.25. Data Input ...................................................................................................................... 301.26. Data Output ................................................................................................................... 31

    2. INTRODUCTION TO VISUAL BASIC................................................................................... 332.1. Creating Your First Macro ............................................................................................. 332.2. Simple User Defined Functions..................................................................................... 33

    2.2.1. Where To Put The Function Code ......................................................................................... 342.2.2. User Defined Funtions And Calcuations ................................................................................35

    2.3. Objects and Collections................................................................................................. 352.3.1. Workbook and Worksheet Object ..........................................................................................362.3.2. Range Object and Cells Property........................................................................................... 37

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

  • 7/30/2019 Introduduction to Financial Programming

    3/55

    3

    2.4.1.Assigning Object Variables and Using Named Argument...................................................... 402.5. Modules and Procedures .............................................................................................. 40

    2.5.1. Modules and Procedures and Their Scope............................................................................402.5.2. Calling Sub Procedures and Function Procedures................................................................ 422.5.3. Passing Argument by Reference or by Value ........................................................................ 43

    2.6. Creating and Managing Arrays...................................................................................... 432.6.1. Declaring an Array With Dim Statement ................................................................................ 442.6.2. Resize an Array With Redim Statement................................................................................. 452.6.3. Manage Dynamic Array .........................................................................................................452.6.4. Create Multi-Dimensional Array .............................................................................................462.6.5. Find The Size of an Array .....................................................................................................472.6.6. Choosing The Right Return Array Size.................................................................................. 482.6.7. Orienting An Array..................................................................................................................49

    2.7. Decision Structures - IF and Select Case ..................................................................... 512.7.1. IF ... Then Statement .............................................................................................................512.7.2. IF ... Then ... Else................................................................................................................... 512.7.3. IF ... Then ... ElseIf................................................................................................................. 522.7.4. Select Case............................................................................................................................ 52

    2.8. Loop Structures ............................................................................................................. 532.8.1. For ... Next .............................................................................................................................532.8.2. For ... Next Loop With Step....................................................................................................532.8.3. Do While ... Loop....................................................................................................................542.8.4. Do Until ... Loop ..................................................................................................................... 542.8.5. Do ... Loop While....................................................................................................................552.8.6. Do ... Loop Until ..................................................................................................................... 55

  • 7/30/2019 Introduduction to Financial Programming

    4/55

    4

    Finance is the art of passing currency from hand to hand until it finally

    disappears.

    Robert W. Sarnoff

  • 7/30/2019 Introduduction to Financial Programming

    5/55

  • 7/30/2019 Introduduction to Financial Programming

    6/55

    6

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

  • 7/30/2019 Introduduction to Financial Programming

    7/55

    7

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

  • 7/30/2019 Introduduction to Financial Programming

    8/55

    8

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

  • 7/30/2019 Introduduction to Financial Programming

    9/55

    9

    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.

  • 7/30/2019 Introduduction to Financial Programming

    10/55

    10

    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 2 3

  • 7/30/2019 Introduduction to Financial Programming

    11/55

    11

    4 5 6

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

    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 4 5 6

    While:

    d = [a ; b]

    gives:

    d =1 2 34 5 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.

  • 7/30/2019 Introduduction to Financial Programming

    12/55

    12

    1.9. Using Portions of Matrices

    Frequently one wishes to reference only a portion of a matrix. MATLABprovides 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 2d(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 2 3

    4 5 6

    d(1,:) equals1 2 3

    d(:,2) equals25

    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:

  • 7/30/2019 Introduduction to Financial Programming

    13/55

    13

    d(2,[2 3]) equals5 6

    d(2, [3 2]) equals

    6 5

    Variables may also be used as "subscripts". Thus:

    ifz = [2 3]

    thend(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 4 5

    Thus:

    d(1, 1:2) equals

    2

    1

    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:

  • 7/30/2019 Introduduction to Financial Programming

    14/55

    14

    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.

  • 7/30/2019 Introduduction to Financial Programming

    15/55

    15

    1.12. Matrix Operations

    Matrix transposition is as easy as adding a prime (apostrophe) to the

    name of the matrix. Thus:

    if:

    x =

    1 2 3

    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.

  • 7/30/2019 Introduduction to Financial Programming

    16/55

  • 7/30/2019 Introduduction to Financial Programming

    17/55

    17

    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 =12

    3 then the statement:

    y =sum(x) + 10

    will produce:

    y =16

    Some functions, such as max provide more than one answer. If such afunction is included in an expression, only the first answer will be used. For

    example:

    if x =

    1 4 3

    the statement:

  • 7/30/2019 Introduduction to Financial Programming

    18/55

    18

    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 4 3

    the statement:

    [y n] = max(x)

    will produce:

    y =

    4n =

    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 anargument to such a function, its procedure is applied separately to each column,

    and a row vector of results returned. Thus:

    if x =1 2 34 5 6

    then :

  • 7/30/2019 Introduduction to Financial Programming

    19/55

    19

    sum(x) =5 7 9

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

  • 7/30/2019 Introduduction to Financial Programming

    20/55

    20

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

    line help system.

    1.15. Logical and Relational Operations on Matrices

    MATLAB offers six relational operators:

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

  • 7/30/2019 Introduduction to Financial Programming

    21/55

    21

    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 23 4

    and B =

    3 1

    2 2

    the statement:

    C = A > B

    produces:

    C =

    0 11 1

    One or both of the operands connected by a relational operator can be a

    scalar. Thus:

    if A =1 2

    3 4

    the statement:

    C = A > 2

    produces:

    C =0 0

    1 1

    One may also use logical operators of which there are three:

  • 7/30/2019 Introduduction to Financial Programming

    22/55

  • 7/30/2019 Introduduction to Financial Programming

    23/55

    23

    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 23 12 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

  • 7/30/2019 Introduduction to Financial Programming

    24/55

    24

    1.18. For Loops

    The most common use of a For Loop arises when a set of statements isto 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

  • 7/30/2019 Introduduction to Financial Programming

    25/55

    25

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

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

  • 7/30/2019 Introduduction to Financial Programming

    26/55

  • 7/30/2019 Introduduction to Financial Programming

    27/55

    27

    1.22. Writing Functions

    The power of MATLAB really comes into play when you add your ownfunctions 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 couldexamine 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.

  • 7/30/2019 Introduduction to Financial Programming

    28/55

    28

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

  • 7/30/2019 Introduduction to Financial Programming

    29/55

  • 7/30/2019 Introduduction to Financial Programming

    30/55

    30

    1.25. Data Input

    The most straightforward way to get information into MATLAB is to type itin "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 200300 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 eachelement 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.

  • 7/30/2019 Introduduction to Financial Programming

    31/55

    31

    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:

  • 7/30/2019 Introduduction to Financial Programming

    32/55

    32

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

  • 7/30/2019 Introduduction to Financial Programming

    33/55

    33

    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 orjust 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 openthe 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 notnecessarily) accepts some inputs and returns a result. A UDF can only return avalue 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. Ifyou attempt to change anything, the function will terminate immediately andreturn 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

  • 7/30/2019 Introduduction to Financial Programming

    34/55

    34

    change anything in Excel. This was fixed with Excel 2002.The following is anexample of a simple UDF that calculates the area of a rectangle:

    Function RectangleArea(Height As Double, Width As Double) As DoubleRectangleArea = Height * Width

    End Function

    This function takes as inputs two Double type variables, Height and Width, andreturns a Double as its result. Once you have defined the UDF in a codemodule, you can call it from a worksheet cell with a formula

    like:=RectangleArea(A1,B1)where A1 and B1 contain the Height and Width ofthe rectangle. Because functions take inputs and return a value, they are notdisplayed 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 theSheet modules and not in the ThisWorkbook module. In the VBA editor, go tothe Insert menu and choose Module. This will insert a new code module into theproject.

    A module can contain any number functions, so you can put many functions intoa single code module. You can change the name of a module from Module1 tosomething more meaningful by pressing the F4 key to display the Propertieswindow and changing the Name property to whatever you want.

    You can call a function from the same workbook by using just the functionname. For example:=RectangleArea(12,34)It is possible, but stronglyrecommended against, to have two functions with the same name is twoseparate code modules within the same workbook. You would call them usingthe 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 moduleand a function (regardless of whether that module contains that function). Doingso will cause an untrappable error.

    You can call a UDF that is contained in another (open) workbook by using theworkbook name in the formula.

  • 7/30/2019 Introduduction to Financial Programming

    35/55

    35

    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 toproperly calculate the result. That means that your UDF should not makeexplicit 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").ValueEnd Function

    In this function, the Width is assumed to be in cell A1. The problem here is thatExcel doesn't know that this function depends on cell A1 and therefore will notrecalculate 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 forceExcel to recalculate a UDF whenever any calculation is made by adding thelineApplication.Volatile Trueas the first line in the function. For example,Function BadRectangleArea(Height As Double) As Double

    Application.Volatile TrueBadRectangleArea = 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. Ingeneral, you shouldn't use Application.Volatile but instead design your UDF toaccept 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 aspecial type of variable that contains both data and codes. A collection is a

  • 7/30/2019 Introduduction to Financial Programming

    36/55

    36

    group of objects of the same class. The most used Excel objects in VBAprogramming are Workbook, Worksheet, Sheet, and Range.

    Workbooks is a collection of all Workbook objects. Worksheets is a collection ofWorksheet objects.

    The Workbook object represents a workbook, the Worksheet object representsa worksheet, the Sheet object represents a worksheet or chartsheet, and theRange 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 Tabindicated. 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 allthe workbooks that are currently opened. Inside of a workbook contains at leastone 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) is not necessary the same sheet asWorksheets("Sheet1").

    Sheets is a collection of worksheets and chart sheets (if present). A sheet canbe 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 theobject. For example:

    Workbooks("Book1").Worksheets("Sheet1")Workbooks("Book2").Worksheets("Sheet1")

    If the object is not qualified, the active or the current object (for exampleworkbook 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 boldfont and white background).

  • 7/30/2019 Introduduction to Financial Programming

    37/55

    37

    * You can change the color of the sheet tabs by right click the tab, choose TabColor, then select the color for the tab.

    The sub routine below shows the name of each sheet in the current openedworkbook. You can use ForEach...Next loop to loop throgh the Worksheetscollection.

    Sub ShowWorkSheets()Dim mySheet As Worksheet

    For Each mySheet In WorksheetsMsgBox 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 ormore contiguous blocks of cells, or a 3-D range. We will show you someexamples 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 asthe 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 projectson this website (very important). The Cells property takes one or two indexesas its parameters.

    For example,

    Cells(index) or Cells(row, column)

    where rowis the row index and column is the column index.

  • 7/30/2019 Introduduction to Financial Programming

    38/55

    38

    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 thecurrent 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 fromA1 to E5.

    Sub CellsExample()For i = 1 To 5

    For j = 1 To 5Cells(i, j) = "Row " & i & " Col " & j

    Next jNext 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 theOffset property can be implemented (assume the current cell before the move isE5):

    ActiveCell.Offset(1,0) = 1 Place a "1" one row under E5 (on E6)

    ActiveCell.Offset(0,1) = 1 Place a "1" one column to the right ofE5 (on F5)

    ActiveCell.Offset(0,-3) = 1 Place a "1" three columns to the left ofE5 (on B5)

  • 7/30/2019 Introduduction to Financial Programming

    39/55

  • 7/30/2019 Introduduction to Financial Programming

    40/55

  • 7/30/2019 Introduduction to Financial Programming

    41/55

    41

    Procedures in Visual Basic can have either private or public scope. Aprocedure with private scope is only accessible to the other procedures in thesame module; a procedure with public scope is accessible to all procedures inin every module in the workbook in which the procedure is declared, and in allworkbooks 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

  • 7/30/2019 Introduduction to Financial Programming

    42/55

    42

    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 amessage box.

    If there are procedures with duplicate names in different modules, you mustneed to include a module qualifier before the procedure name when calling theprocedure.

    For example:

    Module1.ShowSum

  • 7/30/2019 Introduduction to Financial Programming

    43/55

    43

    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'svalue can be changed by the procedure. Passing by reference is the default inVBA. If you do not explicitly specify to pass an argurment by value, VBA willpass 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 themessage box.

    Sub TestPassing1()Dim y As Integery = 50AddNo1 yMsgBox 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 Integery = 50AddNo2 yMsgBox 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 sameintrinsic data type. Each element of an array has a unique identifying index

  • 7/30/2019 Introduduction to Financial Programming

    44/55

    44

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

    2.6.1. Declaring an Array With Dim Statement

    Before signing values to an array, the array needs to be created. Youcan declare the array by using the Dim statement.

    For example, to declare a one-dimensional array with 5 elements, type thefollowing:

    Dim Arr(4)

    The elements index of the array starts from 0 unless Option Base 1 isspecified in the public area (area outside of the sub procedure). If Option Base1 is specified, the index will start from 1.

    The following example assigns values to the array and displays all values in amessage box :

    Option Base 1Sub assignArray( )

    DimArr(5)

    Arr(1) = JanArr(2) = Feb

    Arr(3) = MarArr(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 ofthe first element in the

    array.

  • 7/30/2019 Introduduction to Financial Programming

    45/55

    45

    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 elementvalue of 5 and decided to change the number of the element to 6, you can dothe following to resize the array:

    RedimArr(6)

    We incorporate it into our last example:

    Option Base 1

    Sub assignArray( )'Dim Arr(5)Redim Arr(6)

    Arr(1) = JanArr(2) = FebArr(3) = MarArr(4) = AprArr(5) = MayArr(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 leavingthis 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 thevalues assigned prior to resize the array are erased. Only the value assigned tothe array after resize remains.

    Option Base 1Sub assignArray( )

    RedimArr(5)

    Arr(1) = JanArr(2) = Feb

  • 7/30/2019 Introduduction to Financial Programming

    46/55

    46

    Arr(3) = MarArr(4) = AprArr(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 willremain. For example:

    Option Base 1Sub assignArray( )

    Redim Arr(5)

    Arr(1) = JanArr(2) = FebArr(3) = MarArr(4) = AprArr(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 ourtutorial, example on a two-dimensional array is used. Assume you have data ofa local store's yearly sale in the following table and you want to store the data ina two-dimensional array:

    Year 2003 Year 2004CD Sale 1,000 1,500

    DVD Sale 1,200 2,000

    First we create the array as follow:

  • 7/30/2019 Introduduction to Financial Programming

    47/55

    47

    Dim Arr(2,2)

    Then we assign the values into the array. We treat the first dimension as theyear and the second dimension as the product sale:

    arr(1,1) = 1000arr(1,2) = 1200arr(2,1) = 1500arr(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 _ & "Saleof DVD in 2004 is " & arr(2,2)

    The complete precedure is as followed:

    Option Base 1Sub multDimArray( )

    DimArr(2,2)

    arr(1,1) = 1000arr(1,2) = 1200arr(2,1) = 1500arr(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 ofDVD 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 ofthe 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 arraycan be obtained by using the Ubound function. In our one-dimensional arrayexample, Ubound(arr) is 5.

  • 7/30/2019 Introduduction to Financial Programming

    48/55

    48

    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 Return ValueUBound(A, 1) 100UBound(A, 2) 3UBound(A, 3) 4

    * Example taken from Excel VBA Help section.

    The UBound function is used with the LBound function to determine the size ofan array. Use the LBound function to find the lower limit of an array dimension.

    Statement Return ValueLBound(A, 1) 1LBound(A, 2) 0LBound(A, 3) -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 functionand 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 enterit into a larger range, Excel fills out the unused elements of the range with #N/A

  • 7/30/2019 Introduduction to Financial Programming

    49/55

    49

    errors. If you enter it into a smaller range, you will not get all the values createdby LINEST.

    To mandate the size of the returned array, simply declare the array to that sizeand setting the result of the function to that array. For example,

    Function Test() As VariantDim V() As VariantDim N As LongDim R As LongDim C As LongReDim V(1 To 3, 1 To 4)For R = 1 To 3

    For C = 1 To 4N = N + 1V(R, C) = N

    Next CNext RTest = V

    End Function

    This function simply returns an array with 3 rows and 4 columns that containsthe integers from 1 to 12.

    Returning such a fixed-size array can be useful if the number of results does notvary with the number and/or values of the inputs to the function. However, thisis usually not the case.

    In the majority of circumstances, if your UDF is going to return an array, thatarray will vary in size and the size will depend on any one or more of threethings: the size of the range into which the UDF was entered, the number ofelements passed into the function, and, of course, the nature and function of theUDF itself. The Application.Caller object, when used in a UDF called from aworksheet range, is a Range reference to the range from which your UDF wascalled.

    2.6.7. Orienting An Array

    If your UDF creates a 1-dimensional array as its result, it can orient the array aseither a row vector or a column vector so that is will be properly displayed in theworksheet cells without requiring the user to wrap your UDF result in aTRANSPOSE function.

    If the function was called from a row vector of cells (e.g., A1:E1), it does notneed 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 thearray before returning it to the caller. Note that this should be done only with

  • 7/30/2019 Introduduction to Financial Programming

    50/55

    50

    single-dimensional arrays and only when the UDF is being called from aworksheet range. Therefore, you should first test Application.Caller withIsObject and then test Application.Caller.Rows.Count andApplication.Caller.Columns.Count to test if it is being called from a row orcolumn vector.

    For example,

    Function Test(NN As Long)Dim Result() As LongDim N As LongReDim Result(1 To NN)For N = 1 To NN

    Result(N) = NNext N

    If Application.Caller.Rows.Count > 1 ThenTest = Application.Transpose(Result)

    ElseTest = Result

    End IfEnd Function

    You can, of course, forego this and return the array as-is and leave it up to theuser to use the TRANSPOSE function to properly orient the array.

  • 7/30/2019 Introduduction to Financial Programming

    51/55

    51

    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 blockof statement.

    Example, the following statement set variable Status to "Adult" if the statementis true:

    If Age >= 18 Then Status = "Adult"

    You can also use multiple-line block in the If statement as followed:

    IfAgo >= 18 ThenStatus = "Adult"Vote = "Yes"

    End If

    Note that in the multiple-line block case, End If statement is needed, where thesingle-line case does not.

    2.7.2. IF ... Then ... Else

    The If ... Then ... Else statement is used to define two blocks ofconditions - true and false.

    Example:

    IfAge >=22 Then

    Drink = "Yes"Else

    Drink = "No"End If

    Again, note that End If statement is needed in this case as well since there ismore than one block of statements.

  • 7/30/2019 Introduduction to Financial Programming

    52/55

  • 7/30/2019 Introduduction to Financial Programming

    53/55

    53

    2.8. Loop Structures

    2.8.1. For ... Next

    Use For ... Next loop if the number of loops is already defined andknown. A For ... Next loop uses a counter variable that increases or decreasesin value during each iteration of the loop. This loop structure is being used themost for our examples on this site.

    Here is an example of the For ... Next loop:

    Fori = 1 to 10Cells(i, 1) = i

    Next i

    In this example, i is the counter variable from 1 to 10. The looping process willsend value to the first column of the active sheet and print i (which is 1 to 10) torow 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 thecounter variable.

    For example:

    Fori = 1 to 10 Step 2Cells(i, 1) = i

    Next i

    This looping process will print values with an increment of 2 on row 1, 3, 5, 7and 9 on column one.

    You can also have decrement in the loop by assign a negative value afte theStep keyword.

  • 7/30/2019 Introduduction to Financial Programming

    54/55

    54

    For example:

    Fori = 10 to 1 Step -2Cells(i, 1) = i

    Next i

    This looping process will print values with an increment of -2 starts from 10 onrow 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 theloop. It will run the loop as long as the condition is ture and stops when thecondition becomes false. For Example:

    i = 1Do While i =< 10

    Cells(i, 1) = ii = i + 1

    Loop

    This looping process yields the same result as in the For ... Next structuresexample.

    One thing to be caution is that sometimes the loop might be a infinite loop. Andit happens when the condition never beomes false. In such case, you can stopthe 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 loopuntil the test condition becomes true.

    Example:

    i = 1Do Until i = 11

  • 7/30/2019 Introduduction to Financial Programming

    55/55

    Cells(i, 1) = ii = 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 putthe 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 = 1Do

    Cells(i, 1) = ii = 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 runat least once, you can put the test at the end of loop. The loop will stop whenthe condition becomes true. (compare this loop structure to the Do ... Until

    Loop.)

    For Example:

    i = 1Do

    Cells(i, 1) = ii = i + 1

    Loop Until i = 11