2016-07-24 67 views
0

我是VBA的新手,非常感謝您的幫助。在VBA中使用數組的錯誤

我在寫一個自定義函數。我試圖使用數組來存儲for循環的值,並根據它們在數組上的位置來檢索值。 請參考下面的代碼

Function Amounttopay(Original_Principal As Integer, APR As Double, Npayperyear As Integer, term As Integer, Paydone As Integer) 

Dim strinitialamount() As Integer 
Dim strInterestp() As Integer 
Dim strendamount() As Integer 
Dim i As Integer 

r = (APR/Npayperyear) 
n = Npayperyear * term 
emi = (Original_Principal * r)/(1 - ((1 + r)^(-1 * n))) 

ReDim strinitialamount(n) 
ReDim strInterestp(n) 
ReDim strendamount(n) 

strinitialamount(0) = Original_Principal 
strInterestp(0) = (Original_Principal * r) 
strendamount(0) = (Original_Principal - (emi - strInterestp(0))) 

For i = 1 To (n - 1) 
    strinitialamount(i) = strendamount(i - 1) 
    strInterestp(i) = (strinitialamount(i)) * r 
    strendamount(i) = (strinitialamount(i)) - (emi - strInterestp(i)) 
Next i 

Amounttopay = strendamount(Paydone) 

End Function 
+0

你從哪裏得到這個錯誤嗎? –

+0

在功能輸出。沒有值只顯示#NUM! – Sam

+0

在你的聲明中,你沒有完全的功能。函數x(...東西)作爲整數。 –

回答

1

您需要將其更改爲長,因爲只有整數-32,768之間變爲32,767。

我跑這跟你的價值觀:

Function Amounttopay(Original_Principal As Long, APR As Variant, Npayperyear As Integer, term As Integer, Paydone As Integer) 

    Dim strinitialamount() As Long 
    Dim strInterestp() As Long 
    Dim strendamount() As Long 
    Dim i As Integer 

    r = (APR/Npayperyear) 
    n = Npayperyear * term 
    emi = (Original_Principal * r)/(1 - ((1 + r)^(-1 * n))) 

    ReDim strinitialamount(n) 
    ReDim strInterestp(n) 
    ReDim strendamount(n) 

    strinitialamount(0) = Original_Principal 
    strInterestp(0) = (Original_Principal * r) 
    strendamount(0) = (Original_Principal - (emi - strInterestp(0))) 

    For i = 1 To (n - 1) 
     strinitialamount(i) = strendamount(i - 1) 
     strInterestp(i) = (strinitialamount(i)) * r 
     strendamount(i) = (strinitialamount(i)) - (emi - strInterestp(i)) 
    Next i 

    Amounttopay = strendamount(Paydone) 

    End Function 

    Sub TestFunction() 

    Debug.Print Amounttopay(1000000, 0.1, 12, 1, 6) 
    'Original_Principal = 1000000, APR = 0.1, Npayperyear = 12, term = 1, Paydone = 6 
    End Sub 

我收到這樣的結果:428798