[英]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! 这是我的代码来解决vba上的利率,但是循环将运行到死!
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! 谢谢simoco和谜!
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: 由于在类型转换后将r
声明为Long
,因此循环将变为:
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. 但分配当r = 0.05
,实际值r
将是0
和r=0+0.001
会给你0
为好。 And since r
never increments, this produce infinity loop. 由于r
从不增加,因此会产生无限循环。
BTW , since you operating with double values, for correctness you should also change another values from Long
type to Double
as well 顺便说一句 ,由于您使用double值进行操作,为了正确起见,您还应该将另一个值也从Long
类型更改为Double
The Long vs Double has already been mentioned elsewhere. Long vs Double在其他地方已经被提及。
Next thing is to add DoEvents somewhere in the loop. 接下来的事情是在循环中的某个地方添加DoEvents。 That makes it possible to break script execution and also makes Excel respond (a bit better). 这样就可以中断脚本的执行,也可以使Excel响应(更好)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.