2017-09-25 136 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」變量始終是數組索引之上的整數。

謝謝大家的幫助!