Search code examples
exceldynamic-arraysexcel-2013vba

Why would ReDim throw a Subscript out of range error 9


My code dynamically creates an array in VB Public Function getIndvidualCuts(dblsawKerf As Double) As Double() 'returns and array of of all the cuts

Dim intQuantity As Integer
intQuantity = 0
Dim i As Integer

intQuantity = 0 ' an integer to store the total quanitiy
For i = 0 To Me.getNumCuts() - 1  'for each different cut
    intQuantity = intQuantity + getCutQuantity(i) 'add the cut quantity to the total quantity
Next

Dim total() As Double 'initialize the total cuts array to make room for each individual cut
ReDim total(intQuantity - 1) **error is here**

I don't understand why ReDim throws an Error. I have been searching but all i find are situations where people are using ReDim Preserve If you have a different solution for a dynamic array please share it

Thanks in advance


Solution

  • Examples of invalid array subscripts would be non-integer or negative subscripts. If intQuantity = 0 at any point in your program, then that would produce a subscript for your array of -1. Similarly, if getCutQuantity returns a non-integer, then your array subscript would be a non-integer. Glad that helped.