Excel Formulas MLM
Excel Formulas MLM
Excel Formulas MLM
macros
Mark McIlroy
www.markmcilroy.com
Mark McIlroy 2016. All rights reserved.
ISBN 978-1530079445
Edition 5
Contents
1.
Introduction .......................................................................................................................... 5
2.
2.2
2.3
Basic operations............................................................................................................ 7
2.4
2.5
Logical operators........................................................................................................... 8
2.6
Names .......................................................................................................................... 8
2.7
2.8
2.9
Solver .......................................................................................................................... 10
2.10
3.
3.1
3.2
3.3
3.4
Parameters ................................................................................................................. 14
3.5
Expressions ................................................................................................................ 15
3.6
3.7
3.8
Comments................................................................................................................... 17
3.9
Constants .................................................................................................................... 18
3.10
IF statements .............................................................................................................. 19
3.11
3.12
3.13
3.16
3.16
Debugging ...................................................................................................................... 25
3.16
3.16
3.16
3.17
4.2
4.3
4.1
Resources ...................................................................................................................... 34
1. Introduction
As the title suggests this book is an introduction to writing Excel formulas and macros.
The book assumes only a basic familiarity with Excel.
The book is not intended to be a comprehensive guide to Excel. Excel is a complex system that
has many functions, many of them rarely used.
The book covers the most commonly used functions, and includes everything you need to know
to write basic or advanced formulas and macros.
This book is based on Excel 2013, however the material is relevant to most versions of Excel.
Addition
Subtraction
Multiplication
Division
Exponentiation
Brackets
SUM()
MIN()
MAX()
ROUND()
For example, =MAX( ABS( A1 ) * 0.001, 19.95) will return the value that is 0.1% of cell A1 or
19.95, whichever is greater.
Range formulas such as SUM() require a range cell reference.
7
This is entered in the form A1:A10, for example =SUM(A1:A10). This formula example will add
up all the values in the cells A1 through to A10 and display the value in the cell that has the
formula in it.
As with single cell references you can use Absolute or Relative references in your ranges.
The IF operator allows you to test a condition and return a different result depending on
different conditions.
For example =IF( A1 > 10, 10, A1 )
This formula will test the value of cell A1. If it is greater than 10, the result returned will be 10,
otherwise the result will be the value of cell A1.
Another example, =IF( AND( A1 > 10, B1 < 20), 10, A1 )
As you can see these formulas are starting to get a little complicated. However if you work on a
lot of spreadsheets you will eventually have to write formulas such as these.
The example above tests the values of both cells A1 and B1. If A1 is greater than 10 and B1 is
less than 20, then the result of the formula will be 10, otherwise it will be the value of cell A1.
These operations can be nested to multiple levels in a single formula. If you are going to nest IF
statements they must be in the following form
=IF( condition1, result1, IF( condition2, result2, IF( condition3, result3, result4 )))
2.6 Names
In addition to Absolute and Relative references, you can also refer to other cells in formulas by
giving the cell a name.
This can simply complex spreadsheets, particularly when you are using several worksheets
within a single workbook.
To give a cell a name, click on the cell, right click, and select Define Name.
Then type in a name for the cell and click ok.
For example, define a name for the cell A1 as Fee_rate
You can then type formulas anywhere within the workbook using a syntax such as
=Fee_rate * 2
Goal seek allows you to change a model to produce a certain value, by having Excel
automatically modify an input value.
For example, say that you produce a financial model in Excel that models the income a client
can receive in retirement from their retirement funds.
You want to select the maximum income that your client can draw from their retirement fund,
such that their funds will last until they are 90 years of age.
To achieve this, set up a spreadsheet with the income drawn each year and the declining
balance of their retirement fund.
Then run a Goal Seek function, targeting the fund balance at age 90 cell to zero, by modifying
the income drawn each year cell.
2.9 Solver
Solver is a more powerful version of the Goal seek function.
Solver enables Excel to search for the minimum or maximum value that a model can produce,
by varying one or more input cells.
You can also specify constraints, which involve the minimum or maximum values that are
allowed in various cells within the model when Excel is searching for a solution.
Solver is not installed by default. To activate Solver, click File, Options, Add-Ins, Go, tick the
Solver Add-In box and click ok.
Now you should see Solver on the Data menu.
Please note that having Solver activated may slow down Excel when starting up, so it is
probably a good idea to only install it when you are actually using it.
The Solver screen is fairly self-explanatory.
10
If you have a set of data, such as a set of financial transactions, Excel can summarise your data
into a table.
This is done using the functionality known as a Pivot Table.
For example, you can produce a table that has one row for each month, with totals for that
month, and a total for the year, from a large number of input transactions.
The Pivot Table functionality is relatively complex and varies with each version of Excel.
11
12
Now you should see the value 200 in your new cell.
Congratulations a working VBA macro of your own design.
13
function_name = value
In this example, the value of the variable value will be returned into the cell of the calling
worksheet.
3.4 Parameters
Most macros will have at least one parameter. This is the list of names after the word Function
and the name of the function.
Excel VBA is a line based language. This means that each statement must be on a separate
line. Each statement must start and finish on a single line. If you want to continue an individual
statement on to the next line, place space and an underscore _ at the end of the line.
For example
Public Function my_test_macro(
param1 as double, _
param2 as double, _
param3 as string)
End Function
Take note of the position of every item, including commas. Computer software is demanding and
each item must be entered exactly as defined by the language.
The value entered after the word As is the type of the parameter.
The most commonly used types are the word double, which represents a numeric value, and
string which represents a short item of text.
The word double is shorthand for double precision floating point variable. This is accurate to
approximately 15 digits of precision.
There is also a data type single which is accurate to approximately 7 digits of accuracy. Single
precision data was originally used by programmers to save computer memory but there is no
practical reason in the modern world to use this data type.
Parameters can be used in expressions to calculate values.
14
For example,
Option Explicit
Public Function my_test_macro( param1 as double, param2 as double )
my_test_macro = param1 * param2
End Function
You can test this change to your new macro by entering it as shown, saving the VBA macro
screen, and entering the following in a cell on your new worksheet.
=my_test_macro( A1, A2 )
If you enter values into the cells A1 and A2 the multiplication result of your two values should
appear in the cell that you entered the formula in.
The words Option Explicit at the top of your macro file tells Excel to demand that all the variable
you use in your code are properly declared. It helpful to include this statement.
If you want to change the value of a parameter within your function, it is good programming
practice to use the word ByVal before the parameter definition to indicate that you only want to
use the parameter value in your function, you are not attempting to change its value in the
source worksheet.
For example
Public Function my_test_macro(
3.5 Expressions
VBA expressions follow the natural path that is familiar from mathematical expressions.
For example
my_test_macro = (param1 * param2) / param3 + 10
15
Addition
Subtraction
Multiplication
Division
Exponentiation
Brackets
Concatenate two strings, i.e. add one to the end of the other
A wide range of build-in mathematic functions is available, see the Resources section at the
end of this book.
You can get help on a function by highlighting its name in a VBA code window and pressing F1
Some examples are
Abs( param1 )
Sqr( param1 )
Log( param1 )
16
my_test_macro = value1
End Function
The value of these variables value1 and value2 only applies within the boundaries of the
Function and End Function keywords of this function.
You can use the same names in a different macro function, in which case they will have
separate values from your first function.
By now you have probably noticed that many of the keywords in VBA seem to have almost
meaningless names.
VBA, more formally called Visual Basic for Applications, builds on a long history of the BASIC
language stretching back to the 1960s.
Many of the keywords are based on historical meanings.
For example, the word Dim which is used for declaring local variables is short for the word
Dimension, which was initially used to specify the dimensions of an array.
3.8 Comments
You can enter comments within your code files that are intended for a human reader, and are
ignored by the program system.
This is done by typing a single quote character.
17
Anything after the quote character to the end of the line will be displayed in green and is ignored
by Excel when it is executing your code.
For example:
param1 as double, _
param2 as double, _
param3 as string)
main calculation
my_test_macro = value1
End Function
Comments are extremely useful when you come back to modify the code on a future date, or
when some other person needs to work on your code.
3.9 Constants
As you do more programming you will find that you use fixed values quite often.
There is a way to specify fixed values within your code so that they are easier to read and
modify. This is done with constants
Constants are specified by placing code in this format at the top of the code window.
Const CONSTANT_NAME As DATA_TYPE = VALUE
For example
Const CURRENT_MODELS_NAME As String = "Portfolios 17.11.2015.xlsm"
You can then use this name in your code in the place of the actual value, such as the code
below:
18
workbook_name = CURRENT_MODELS_NAME
Constants make your code easier to read and modify and reduces the chance of bugs occurring
in your code. It is recommended that everywhere you use a constant value you declare it at the
top of the file.
3.10 IF statements
The VBA code that we have looked at so far uses variables, functions and mathematical
operators.
However thus far you probably could have used a standard Excel worksheet to produce the
same results.
The following sections identify the more powerful features of VBA.
An if statement allows you to test a condition.
For example consider the macro code below
If param1 > 10 Then
my_test_macro = 10
End If
You can also specify an alternative expression, such as the code below.
If param1 > 10 Then
my_test_macro = 10
Else
my_test_macro = 20
End If
This statement will compare the value of param1 to 10, and if it is greater than ten it will set your
result to 10, otherwise it will set it to 20.
It is also possible to chain if statements into longer sets of statements such as the example
below
19
my_test_macro = 40
Else
my_test_macro = 50
End If
20
equal
a <> b
not equal
a<b
less than
a <= b
a >b
greater than
a >= b
a And b
both TRUE
a Or b
Not a
if a is FALSE
You can declare variables that will the True or False using a statement as below
Dim found as Boolean
Some developers prefer to use integer variables which have the same effect, such as
Dim found as Integer
21
For example
count = 0
While count < 10
code here
count = count + 1
Wend
In this example, the code inside the loop will be executed 1000 times
22
Loops can be nested inside each other in any combination, such as in the example below.
For day = 1 to 31
For account = 1 to 100
code here
Next
Next
You should be aware that code inside nested loops can be execute an large number of times, so
this may slow your system down somewhat.
In the following example, the code inside the inner loop will be executed 1,000,000 times.
For a = 1 to 1000
For b = 1 to 1000
code here
Next
Next
for example
value1 = Application.WorksheetFunction.Norm_S_Dist(da, True)
3.14
Good programming practice suggests that a function should derive all the data that it needs from
the values of its parameters.
However there are cases where you might need to access the values on a worksheet directly
from within a macro function, such as when you need to search a table of values that appears on
a worksheet.
23
The following example accesses the value in cell row r, column 2 on a worksheet directly.
Const MODELS_NAME as string = Portfolios 15.12.16
Const YIELDS as string = "Yields & MER"
If you want to use this method you will need to have the workbook open in Excel when you run
the macro.
3.16
The above examples explain how to write a save a VBA macro within a workbook.
However you might wish to save a macro in a workbook and then run this macro from other
workbooks.
This can be done by writing and saving the workbook that has the macro in it. Open this
workbook in Excel, and make sure that you click on the Enable Macros button if it appears
when you open the workbook.
Then go to the new workbook that you are going to call the function from.
Click on the cell that you want to use to call the macro.
Click on the Fx button on the menu bar.
This will bring up a dialog box.
Click on the Or select a category drop-down list.
Scroll down and click on User defined
You should now see a list of all available macros that you have written that are in open
workbooks, and you can simply click on the appropriate one.
It is also possible to make macros permanently available by making your own Excel Add-in.
This is done by saving your macro workbook with a file type of Excel Add-in
Then go to
File
24
Options
Add-Ins
Manage Excel Add-ins Go
And click on the name of your new Add-in file.
3.16
Debugging
When you are looking at a VBA code window, you can use the following shortcut keys for
debugging the code.
F9
Inserts a breakpoint on the line the cursor is on. Excel will stop executing the
macro when it reaches this line, and you can examine the value of various
variables.
Shift-F9
F8
Execute the line of code that the cursor is stopped on and step to the next line.
F5
Continue executing the macro after it has stopped, stopping only at the next
breakpoint line or the end of the macro.
3.16
Error handling
By default, when a macro encounters an error, it simply stops without displaying any error
message. This is not very helpful.
You can display an error message for errors by using the following code.
At the top of your function, add the following line of code
On Error GoTo err_code
25
Exit Function
err_code:
MsgBox Err.Description
This code will have the effect of displaying an error message whenever the Excel macro
encounters an error and stops.
3.16
Opens a file for writing to. Ensure that the folder that you use is one that you have permission to
write to.
Close #1
MsgBox "Finished"
3.16
As you write more complex and larger blocks of code, you will eventually have to break your
VBA module files up into a number of functions and subroutines.
A subroutine is a block of code that you can call multiple times within your program.
26
27
3.17
Entire books can, and have, been written on good programming practice.
The author has written several books on programming and Computer Science for the interested
reader.
However, Excel macros are usually written by practitioners in Finance, Social Sciences etc
rather than professional programmers, so a few basic notes only may be in order.
Make sure that you lay out the code with plenty of blank lines between statements. This is
extremely important and will ensure that a reader has some chance of understanding the code
when they come back to work on it at a future date.
When you have an If statement or While loop, indent the code inside the statement by one tab
stop. This is very important to enhance the readability of the code.
Include plenty of comments. You really cant have too many comments.
Dont use a variable to mean two different things inside a function. When this occurs declare two
separate variables and use them separately.
Try to use names for variables that have some meaning. Avoid generic names such as x, y ,a
and b unless they actually have some meaning in the context of the particular function.
28
'
'
'
'
'
'
'
29
low As Double
high As Double
vol As Double
premium As Double
diff As Double
da As Double
db As Double
30
Wend
call_implied_volatility = vol
End Function
31
32
33
5 Resources
A number of websites have useful information for the VBA macro programmer.
Pressing F1 in the Excel macro window will bring up the Microsoft help system. For help on a
particular function or keyword, highlight the word before pressing F1.
34
35