PDA

View Full Version : Help - Run-time error '9': Subscript out of range



4907
10-25-2016, 06:43 AM
Sub Combo()
n = Cells(Rows.Count, "A").End(xlUp).Row - 1
Dim step(), x(), y()
ReDim step(1 To n + 2)
ReDim x(1 To n)
ReDim y(1 To n)
'reads step sizes
For i = 1 To n
step(i) = Cells(i + 2, 1) - Cells(1 + 1, 1)
x(i) = Cells(i + 1, 1)
y(i) = Cells(1 + 1, 2)
Next i
For i = 1 To n
'Simposon's 3/8ths
If Abs(step(i) - step(i + 1)) < 0.0001 And Abs(step(i) - step(1 + 2)) < 0.0001 Then
a = Cells(i + 1, 1)
b = Cells(i + 4, 1)
sum = sum + (b - a) * (y(i) + 3 * y(i + 1) + 3 * y(1 + 2) + y(1 + 3)) / 8
i = i + 2
'Simpsons 1/3rd
ElseIf Abs((step(i)) - step(i + 1)) < 0.0001 Then
a = Cells(i + 1, 1)
b = Cells(i + 3, 1)
sum = sum + (b - a) * (y(i) + 4 * y(i + 1) + y(i + 2)) / 6
'Run-time error '9':Subscript out of range ^^^
i = i + 1
'Trapezoid
ElseIf step(i) > 0 Then
a = Cells(i + 1, 1)
b = Cells(i + 2, 1)
sum = sum + (b - a) * (y(i) + y(i + 1)) / 2
End If
Next i
Cells(3, "E") = sum
End Sub

snb
10-25-2016, 07:07 AM
On error resume next

F8

Paul_Hossler
10-25-2016, 07:22 AM
1. Please use the [#] icon to add [ CODE ] .... [ / CODE ] tags to make the macro more readable

2. A little bit of data or a sample workbook will help

3. Guessing,

a. you ReDim x() and y() to 1 to n
b. you loop I from 1 to n
c. you use y(I+2), so when I=n, I+2 is out of the subscript range

4. Without data and stepping through, it's hard to tell more than that




Option Explicit
Sub Combo()
Dim n As Long, i As Long
Dim step() As Double, x() As Double, y() As Double
Dim a As Double, b As Double
n = Cells(Rows.Count, "A").End(xlUp).Row - 1
ReDim step(1 To n + 2)
ReDim x(1 To n)
ReDim y(1 To n) '<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

'reads step sizes
For i = 1 To n
step(i) = Cells(i + 2, 1) - Cells(1 + 1, 1)
x(i) = Cells(i + 1, 1)
y(i) = Cells(1 + 1, 2)
Next i

For i = 1 To n '<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
'Simposon's 3/8ths
If Abs(step(i) - step(i + 1)) < 0.0001 And Abs(step(i) - step(1 + 2)) < 0.0001 Then
a = Cells(i + 1, 1)
b = Cells(i + 4, 1)
Sum = Sum + (b - a) * (y(i) + 3 * y(i + 1) + 3 * y(1 + 2) + y(1 + 3)) / 8
i = i + 2
'Simpsons 1/3rd
ElseIf Abs((step(i)) - step(i + 1)) < 0.0001 Then
a = Cells(i + 1, 1)
b = Cells(i + 3, 1)
Sum = Sum + (b - a) * (y(i) + 4 * y(i + 1) + y(i + 2)) / 6 ' <<<<<<<<<<<<<<<<<<<<<<<<<<<<
'Run-time error '9':Subscript out of range ^^^
i = i + 1

'Trapezoid
ElseIf step(i) > 0 Then
a = Cells(i + 1, 1)
b = Cells(i + 2, 1)
Sum = Sum + (b - a) * (y(i) + y(i + 1)) / 2
End If
Next i
Cells(3, "E") = Sum
End Sub

mancubus
10-25-2016, 07:34 AM
"Step" is a vba keyword.