i have got the following problem. I am creating an excel worksheet with active x elements to calculate several values (for a class in university). And in the following code i sometimes (not everytime) get the runtime error 9 that the index is out of range (hopefully i translated it correctly into english). I am new to vba. I know that there are several similar problems already asked but i have a huge problem to adapt the solutions to my code as i don't really understand either the problem in my code as also the solutions of their problems.
I marked the line for which the error occurs with stars.
I would be really thankful if anybody could explain, why this problem occurs in my code sometimes and how to solve it properly. Thank you in advance.
Here's the code:
Sub calcinull()
Dim ione(4), itwo(4), ii, ints(4), cs(4), io, it As Double
Dim a, b, c As Double
ione(0) = 0
ione(1) = 10
ione(2) = 20
ione(3) = 30
ione(4) = 40
itwo(0) = 100
itwo(1) = 90
itwo(2) = 80
itwo(3) = 70
itwo(4) = 60
For b = 0 To 4
ii = ione(b) + (((itwo(b) - ione(b)) * (NPV(ione(b))) / (NPV(ione(b)) - NPV(itwo(b)))))
ints(b) = ii
cs(b) = NPV(ii)
Next b
Dim AbsInt(4), AbsCs(4) As Double
For a = 0 To 4
AbsInt(a) = VBA.Abs(ints(a))
AbsCs(a) = VBA.Abs(cs(a))
Next a
Dim pos As Integer
pos = Application.Match(Application.Min(AbsCs), AbsCs, 0)
*ii = ints(pos)*
If NPV(ii) > 0 Then
io = ii
If pos > 0 Then
it = itwo(pos - 1)
Else
it = itwo(0)
End If
ElseIf NPV(ii) < 0 Then
it = ii
If pos > 0 Then
io = ione(pos - 1)
Else
io = ione(0)
End If
ElseIf NPV(ii) = 0 Then
inull = ii
End If
For c = 1 To 30
Do Until (NPV(io) - NPV(it)) <> 0
io = io - 0.1
it = it + 0.1
Loop
ii = io + (((it - io) * (NPV(io)) / (NPV(io) - NPV(it))))
If NPV(ii) > 0 Then
io = ii
If it > (io + 0.5) Then
it = it - 0.5
End If
ElseIf NPV(ii) < 0 Then
it = ii
If io < (it - 0.5) Then
io = io + 0.5
End If
ElseIf NPV(ii) = 0 Then
inull = ii
Exit For
End If
Next c
inull = ii
End Sub
As ints
is an array with 5 elements (0..4), probably pos
is > 4 when this error occurs.
If you can't tell why, maybe put something like this behind the Match
-Statement and set a breakpoint to the print
while testing.
if pos < 0 or pos > 4 then
debug.print pos & " is off"
end if
Alright guys, i solved it. The problem was, that the arrays uses indices from 0 to x, whereas the position gives the nth position of the array, which means, that my "pos"-variable is always one integer above the array-index.
Thank you all for your help!
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.