简体   繁体   中英

run loop step on decimal on vba get stuck

Here is my code to solve interest rate on vba, but the loop will run to the death!

Please help me to find what the problem is on the code!

Thank you very much!!!

Sub rate()

    Dim r As Long
    Dim y As Long
    Dim term0 As Long
    Dim term1 As Long
    Dim term2 As Long
    Dim term3 As Long
    Dim term4 As Long

    For r = 0.05 To 0.08 Step 0.001
        term0 = 10000
        term1 = 14000 / (1 + r)
        term2 = 18000 / (1 + r) ^ 2
        term3 = 22000 / (1 + r) ^ 3
        term4 = 25000 / (1 + r) ^ 4

        y = term0 + term1 + term2 + term3 + term4
        If y <= 75000 Then
            MsgBox (r)
        End If
    Next r

End Sub

Thank you simoco and Enigmativity!

After revision, here is the code which works great!

Sub rate()

    Dim r As Double
    Dim y As Long
    Dim term0, term1, term2, term3, term4 As Long

    r = 0.06
    Do
        r = r + 0.00001
        term0 = 10000
        term1 = 14000 / (1 + r)
        term2 = 18000 / (1 + r) ^ 2
        term3 = 22000 / (1 + r) ^ 3
        term4 = 25000 / (1 + r) ^ 4

        y = term0 + term1 + term2 + term3 + term4

    Loop Until y <= 75000

    Cells(11, 11) = r
    Cells(14, 12) = term0
    Cells(15, 12) = term1
    Cells(16, 12) = term2
    Cells(17, 12) = term3
    Cells(18, 12) = term4
    Cells(20, 12) = y

End Sub

Change

Dim r As Long

to

Dim r As Double

Since you declared r as Long after type casting your loop would become:

For r = 0 To 0.08 Step 0.001
    'code
Next r

but when assigning r = 0.05 , actual value of r would be 0 and r=0+0.001 would give you 0 as well. And since r never increments, this produce infinity loop.

BTW , since you operating with double values, for correctness you should also change another values from Long type to Double as well

The Long vs Double has already been mentioned elsewhere.
Next thing is to add DoEvents somewhere in the loop. That makes it possible to break script execution and also makes Excel respond (a bit better).

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