[英]VBA Runtime Error 9 (Excel 2007)
我有以下問題。 我正在創建一個具有活動x元素的excel工作表,以計算多個值(針對大學中的一門課)。 在以下代碼中,有時(並非每次)我都會得到運行時錯誤9,表明索引超出范圍(希望我將其正確翻譯為英語)。 我是vba的新手。 我知道已經問過幾個類似的問題,但是我有一個很大的問題要使解決方案適應我的代碼,因為我既不真正理解我的代碼中的問題,也不真正理解它們的問題。
我用星號標記了發生錯誤的行。
如果有人能解釋,我會非常感激,為什么有時在我的代碼中出現此問題,以及如何正確解決它。 先感謝您。
這是代碼:
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
由於ints
是一個包含5個元素(0..4)的數組,因此發生此錯誤時pos
可能> 4。
如果您不知道為什么,可以在Match
-Statement后面放置類似的內容,並在測試時為print
設置斷點。
if pos < 0 or pos > 4 then
debug.print pos & " is off"
end if
好的,我解決了。 問題是,數組使用從0到x的索引,而該位置給出了數組的第n個位置,這意味着我的“ pos”變量始終比array-index高1個整數。
謝謝大家的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.