No risk, no fun!

Dynamic named range change

Sometimes, in financial modelling in Excel, is very useful to implement changing of named ranges dynamically. E.g. when you're building of matrix of IRRs and margins, which depends on NOI (net operating income) and investment budget and as a result you have matrix with solutions like, "show me all possibilites with IRR > 10% and margin > 20%. At the end you can receive a function describing all solutions using built-in Linest() function.

The problem arrise, when you want to play with initial variables like: exchange rate or interest rate which have impact on number of solutions, so we have to be able to add or remove some cells used by Linest().


First we need to put named ranges as a argument for our function:

Linest(known_y;known_x)

Then, in the sheet where are initials variables are we have to put following code:

1
2
3
4
5
6
7
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$E$13" Or Target.Address = "$E$43" Then
    LinearRegressionArgsRedefine
Else
End If
Exit Sub
End Sub

First sub is checking if our cells with initials variables have changed. If yes, second sub is firing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Sub LinearRegressionArgsRedefine()
Application.ScreenUpdating = False
 
ActiveWorkbook.Names("known_y").Delete
ActiveWorkbook.Names("known_x").Delete
 
Dim r As Range
Dim cell As Range
Dim wks As Worksheet
Dim startRow As Integer
 
Set r = Worksheets("formula").Range("H8:H34")
For Each cell In r
    If cell.Value <> 0 Then
        startRow = cell.Row
        Dim startY As Variant
        Dim stopY As Variant
        Dim startX As Variant
        Dim stopX As Variant
        startY = "$H$" & startRow
        stopY = "$H$34"
        startX = "$G$" & startRow
        stopX = "$G$34"
        RangeY = "=formula!" & startY & ":" & stopY
        RangeX = "=formula!" & startX & ":" & stopX
 
    ActiveWorkbook.Names.Add Name:="known_y", RefersTo:=CStr(RangeY)
    ActiveWorkbook.Names.Add Name:="known_x", RefersTo:=CStr(RangeX)
 
Exit For
Else
End If
Next
Application.ScreenUpdating = True
End Sub

It removes now outdated named ranges and checking which cells have got solutions which suits us and creates updated named ranges. Linest function is recalculating accordingly. That's all.

Popularity: 83% [?]

One Response to “ Dynamic named range change ”

  1. Kredyty says:

    Dzieki za ten Blog, Dodalam go do ulubionych.

Leave a Reply

Powered by Wordpress | Designed by Elegant Themes