简体   繁体   中英

Goal seek exit year rises infinitely

I am brand new to VBA. I have a basic excel 2010 project finance model I made specifically for practicing goal seek macros and learning some VBA. I used this macro (taken from a workbook made by someone else) and successfully adapted it to my own to find the PPA rate by entering the desired IRR.

However, I am trying to adapt it again to find the exit year by entering desired IRR, and it causes the exit year to increase infinitely. Ideally I want it to only be able to seek for a year within a specified range and only round numbers (ie years 1-25 only)

Private Sub CommandButton2_Click()


Equity_IRR_New = Range("D21").Value
Equity_IRR_Old = Range("C23").Value
Tariff_New = Worksheets("Sheet1").Range("C21").Value
Tariff_Old = 0
'Worksheets("Sheet1").Range("C21").Value = 100000'
If (Equity_IRR_New < Equity_IRR_Old) Then
    Do Until (Equity_IRR_New >= Equity_IRR_Old)
        ExitYr_Old = Worksheets("Sheet1").Range("C21").Value
        ExitYr_New = ExitYr_Old * (0.999)
        Worksheets("Sheet1").Range("C21").Value = ExitYr_New
        Equity_IRR_Old = Range("C23").Value
    Loop
End If

If (Equity_IRR_New > Equity_IRR_Old) Then
    Do Until (Equity_IRR_New <= Equity_IRR_Old)
        ExitYr_Old = Worksheets("Sheet1").Range("C21").Value
        ExitYr_New = ExitYr_Old * (1.001)
        Worksheets("Sheet1").Range("C21").Value = ExitYr_New
        Equity_IRR_Old = Range("C23").Value
    Loop
End If

Range("C21").Value = ExitYr_New


End Sub

Thank you in advance

The problem is because your loop condition is looking for Equity_IRR_New <= Equity_IRR_Old , and that condition will never be met since you're INCREASING Equity_IRR_New in each loop iteration.

The way you have it setup based on your comment "'Worksheets("Sheet1").Range("C21").Value = 100000'", it will only enter the second "if" block, ie:

If (Equity_IRR_New > Equity_IRR_Old) Then
    Do Until (Equity_IRR_New <= Equity_IRR_Old)
        ExitYr_Old = Worksheets("Sheet1").Range("C21").Value
        ExitYr_New = ExitYr_Old * (1.001)
        Worksheets("Sheet1").Range("C21").Value = ExitYr_New
        Equity_IRR_Old = Range("C23").Value
    Loop
End If

As I said above, the value of Equity_IRR_New is ever increasing with every loop, because of the statement ExitYr_New = ExitYr_Old * (1.001) , and therefore, if it's not less than or equal to Equity_IRR_Old to start of with, it will never be. What is the initial value in cell "C23"?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM