简体   繁体   中英

VBA Excel Overflow error

Can someone please explain the fault in this code? I am getting overflow error. First i thought this might be due to large input values of n1, n2 i am giving in (order 10000), even after decreasing the values of them to few hundred's i am getting this error.

Private Sub CommandButton1_Click()       
Dim Ds1, Ds2, Ds3, Ds4, Ds5, n1, n2, n3, n4, n5, C, m, a0, w, D, N, i, Pi As Double  
Pi = 3.14159265359
Ds1 = TextBox8.Text
n1 = TextBox10.Text
Ds2 = TextBox13.Text
n2 = TextBox14.Text
Ds3 = TextBox17.Text
n3 = TextBox18.Text
Ds4 = TextBox11.Text
n4 = TextBox12.Text
Ds5 = TextBox15.Text
n5 = TextBox16.Text
C = TextBox20.Text
m = TextBox19.Text
a0 = TextBox22.Text
w = TextBox21.Text`  
D = Sqr(((n1 * (Ds1 ^ 2)) + (n2 * (Ds2 ^ 2)) + (n3 * (Ds3 ^ 2)) + (n4 * (Ds4 ^ 2)) + (n5 * (Ds5 ^ 2))) / (n1 + n2 + n3 + n4 + n5))
N = n1 + n2 + n3 + n4 + n5  

ReDim af1(N) As Double  
ReDim Y(N) As Double  

af1(0) = a0

For i = 1 To N    
Y(i) = 1.12 - (0.23 * (af1(i - 1) / w)) + (10.55 * ((af1(i - 1) / w) ^ 2)) - (21.72 * ((af1(i - 1) / w) ^ 3)) + (30.39 * ((af1(i - 1) / w) ^ 4))  
af1(i) = af1(i - 1) + (C * (D ^ m) * (Pi ^ (m / 2)) * ((af1(i - 1)) ^ (m / 2)) * (Y(i) ^ m))    
Next i      

TextBox11.Text = af1(N)
End Sub

Try declaring all your variable as Double. At the moment only Pi is a double. If you say

Dim D1, D2 as Double

then only D2 is a Double. D1 is a Variant. It should be

Dim D1 as Double, D2 as Double

etc.

Also cast your textbox values:

Ds1 = CDbl(TextBox8.Text)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM