25
Macros & User defined function with VBA

Macros & User defined function (VBA).pptx

Embed Size (px)

Citation preview

Page 1: Macros & User defined function (VBA).pptx

Macros & User defined function with VBA

Page 2: Macros & User defined function (VBA).pptx

Why Macros / Functions? Automating a task performed frequently Automating repetitive operations Creating customized functions

Simplified front end Help other users

Complicated sequence of calculations can be replaced by function entries

Page 3: Macros & User defined function (VBA).pptx

Macros

Page 4: Macros & User defined function (VBA).pptx

Recording Macros To start the macro recorder, choose

View➪Macro➪Record New Macro. The Record Macro dialog box presents several options: Macro Name: The name of the macro. Shortcut Key: You can specify a key combination

that executes the macro. The key combination always uses the Ctrl key.

Store Macro In: The location for the macro. Description: A description of the macro. By

default, Excel inserts the date and your name. You can add more information if you like.

Page 5: Macros & User defined function (VBA).pptx

Recording a macro: Example 1 Record a macro that changes the formatting for the

current range selection. The macro makes the selected range use Arial 16-point type, boldface, and the color red. Select the cell that contains the value or text Select View➪Macro➪Record New Macro Enter a new name for the macro Assign this macro to the shortcut key Ctrl+Shift+F by

entering Shift+F in the edit box labeled Shortcut Key Click OK. This closes the Record Macro dialog box. Select Format➪Cells and then click the Font tab. Choose Arial

font, Bold, and 16-point type, and make the color red. Click OK to close the Format Cells dialog box.

The macro is finished, so click the Stop Recording button on the Stop Recording toolbar (View➪Macro➪Stop Recording).

Page 6: Macros & User defined function (VBA).pptx

Recording a macro: Example 2 Converting formulas into values is usually a

two-step process in Excel: Copy the range to the Clipboard. Choose Edit -> Paste Special (with the Values

option selected) to paste the values over the formulas.

Page 7: Macros & User defined function (VBA).pptx

User defined Functions

Page 8: Macros & User defined function (VBA).pptx

Structure of a function Where to define functions:

Alt + F11 Within the VBA editor, select Insert | Module from the

menu Has three elements

Header line with name of function and list of parameters Closing line Program lines (instructions) between header and closing

line Ex: Function myFunction(p)…End Function

Page 9: Macros & User defined function (VBA).pptx

Ex: A simple functionFinding the square:Function mySqr(p)mySqr = p * pEnd Function

Find difference between two numbers:Function myDiff(p1,p2)myDiff = p1 – p2End Function

Page 10: Macros & User defined function (VBA).pptx

Conditional Execution – Simple IF If then else… Structure

If <condition> Then <If True> Else <If False> Ex: If t-stat is greater than 1.96 return 1 else

return 0

Function myTstat(p)If p > 1.96 then myTstat = 1 else myTstat = 0End Function

Page 11: Macros & User defined function (VBA).pptx

Conditional Execution - Block IF If more than one statement is to be

conditionally executed Structure

If <condition> Then <Instruction>

ElseIf <condition> Then <Instruction>

[Any number of ElseIfs ]

Else <Instruction>

End If

Ex: Deposit Interest Rate

< 10,000 5%

> 10,000 & < 50,000 5.5%

>50,000 & < 1,00,000 6%

> 1,00,000 6.5%

Page 12: Macros & User defined function (VBA).pptx

Conditional Execution – Block IFFunction myRates(deposit)

If deposit < 10000 Then

myRates = 0.05

ElseIf (deposit >= 10000) And (deposit < 50000) Then

myRates = 0.055

ElseIf (deposit >= 50000) And (deposit < 100000) Then

myRates = 0.06

Else

myRates = 0.065

End If

End Function

Page 13: Macros & User defined function (VBA).pptx

Conditional Execution – Select Case Execute a statement from a set of statements based on

value of an expression Structure

Function mySelect(p)Select Case pCase 1

<statement>Case 2

<statement>…Case Else

<statement>End Select

End Function

Page 14: Macros & User defined function (VBA).pptx

Conditional Select – Select Case Ex:Function myselect(p)

Select Case p

Case Is < 10000

myselect = 0.05

Case Is < 50000

myselect = 0.055

Case Is < 100000

myselect = 0.06

Case Else

myselect = 0.065

End Select

End Function

Page 15: Macros & User defined function (VBA).pptx

Excel functions in VBA Compute the price of a call option using Black-Scholes

options pricing formulae. The inputs to the model Stock Price – 100

Strike Price – ATM

Volatility – 20%

Risk Free rate – 5%

Time to Maturity – 6 Months

Function BS(s, k, v, r, t)

d1 = (Application.WorksheetFunction.Ln(s / k) + (r + (v ^ 2) / 2) * t) / (v * Sqr(t))

d2 = d1 - (v * Sqr(t))

BS = (Application.WorksheetFunction.NormSDist(d1) * s) - (Application.WorksheetFunction.NormSDist(d2) * k * Exp(-r * t))

End Function

Page 16: Macros & User defined function (VBA).pptx

Loops – For Next Repeats a set of statements for a defined

number of times Compute FactorialFunction myFactorial(p)j = 1

For i = 1 To p Step 1 j = j * iNext i

myFactorial = jEnd Function

Page 17: Macros & User defined function (VBA).pptx

Calling User-defined functions Compute factorial using recursive function call

Function myFactorial2(p)If p = 0 Then myFactorial2 = 1Else myFactorial2 = myFactorial2(p - 1) * pEnd IfEnd Function

Page 18: Macros & User defined function (VBA).pptx

Variables Variables are used to store and manipulate data Defining a variable

Dim <variable name> As <variable type>

Ex: Dim Temp As Integer Commonly used variable typeVariable Type

Range

Boolean True / False

Integer -32,768 to 32,767

Long (Integer) -2,147,483,648 to 2,147,483,647

Double (Floating)

-1.798 E 308 to -4.941 E -324 (-ve)

4.941 E -324 to 1.798 E 308 (+ve)

Date Jan 1, 100 to December 31, 9999

String Text

Variant (default)

Any numeric value up to range of a Double. Can also hold text / Array / Matrix

Page 19: Macros & User defined function (VBA).pptx

Arrays Compute PV of a set of cash flows.

Inputs: cash-flows and discount rate

Function pvarray(myCF As Variant, n As Double)Dim rws As Integer, cls As Integer, i As Integer, j As Integer, temp As

DoubleDim tempCF As VarianttempCF = myCFrws = UBound(tempCF, 1)cls = UBound(tempCF, 2)temp = 0For i = 1 To cls For j = 1 To rws temp = temp + (tempCF(j, i) / (1 + n) ^ j) Next jNext ipvarray = tempEnd Function

Page 20: Macros & User defined function (VBA).pptx
Page 21: Macros & User defined function (VBA).pptx

Backup

Page 22: Macros & User defined function (VBA).pptx

Conditional Execution – Nested IFFunction myRates2(deposit)

If (deposit < 10000) Then

myRates2 = 0.05

Else

If (deposit < 50000) Then

myRates2 = 0.055

Else

If (deposit < 100000) Then

myRates2 = 0.06

Else

myRates2 = 0.065

End If

End If

End If

End Function

Page 23: Macros & User defined function (VBA).pptx

Loops – Do While Executes statement while the condition is true Compute factorialFunction myFactorial2(p)If p < 2 Then myFactorial2 = 1Else i = 1 j = 1 Do While i <= p j = j * i i = i + 1 Loop myFactorial2 = jEnd IfEnd Function

Page 24: Macros & User defined function (VBA).pptx

Loops – Do Until Executes statement until the condition is met Compute factorialFunction myFactorial3(p)If p < 2 Then myFactorial2 = 1Else i = 1 j = 1 Do Until i > p j = j * i i = i + 1 Loop myFactorial2 = jEnd IfEnd Function

Page 25: Macros & User defined function (VBA).pptx

Arrays A group of variables sharing the same name & type and

referenced by an index Declaring an arrayDim myArray(5) Array index starts from 0 Declaring an array with index boundariesDim myArray(2 To 5) Identifying the bounds of an arrayLBound(myArray)UBound(myArray) Multi-dimension arrayDim myArray(5,5)Dim myArray(1 To 5, 1 to 5)