2017-09-25 133 views
0

我有以下问题。我创建了一个带有活动x元素的excel工作表来计算几个值(对于大学中的一个班级)。在下面的代码中,我有时(并非每次)都会得到运行时错误9,指出索引超出范围(希望我将它正确地翻译成英文)。我是vba新手。我知道有几个类似的问题已经被问到,但是我有一个很大的问题来适应我的代码,因为我不太了解代码中的问题以及他们问题的解决方案。VBA运行时错误9(Excel 2007)

我标记了与星星发生错误的行。

如果有人可以解释,为什么在我的代码中有时会出现这个问题,以及如何正确解决问题,我会非常感激。 预先感谢您。

下面的代码:

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 
+0

不'NPV'需要2个参数吗? 'Rate'和'ValueArray()'? –

+0

净现值是一种UDF,它要求利率作为变量,因为该变量用于折现给定的现金流量。我不是很好,习惯了vba,但我真的不明白ValueArray如何用于NPV。你能向我解释你的想法吗? 非常感谢您提前。 –

回答

0

ints由于是具有5个元素(0..4)的阵列,大概是pos> 4时,会发生该错误。

如果你不能说清楚为什么,可能会在Match-语句后加上类似的内容,并在测试时将断点设置为print

if pos < 0 or pos > 4 then 
    debug.print pos & " is off" 
end if 
+0

好的。这个问题似乎有点合乎逻辑,但问题是,它为什么会发生。特别是因为之前的数组(“ints”和“cs”及其“AbsInt”和“AbsCs”)的长度与它们在同一个循环中填充的长度相同。并且“pos”变量应该给出Cs的绝对值的最小值的位置,然后作为回报,我需要在这个位置上的Int-Array的值。我不明白代码的错误。 :( –

0

好吧伙计们,我解决了它。问题是,数组使用从0到x的索引,而位置给出数组的第n个位置,这意味着我的“pos”变量始终是数组索引之上的整数。

谢谢大家的帮助!