Question

I am trying to run a Simple formula to remove blank entries from an array. The array I am using is loaded from a field in a data table I have set up in excel called TY. The name of this field is TY[L3 Number]. I want to keep this array dynamic, as it might change as user add or delete rows from the data table. The test data I am using has 218 rows, 210 of which have duplicate entries (which I will want to remove later), and 8 entries of "".

When running the macro, I get a run-time error 9 "subscript out of range" on the first line of my if statement.

I have literally spent hours trying to understand why VBA is giving me this error. My understanding is that this is due to an array not correctly sized to handle the data being passed to it. I have used the debug window to verify that both arrays are sized correctly.

I am pretty new to programming, and teaching myself as I go, but I just kind find the solution to this one on my own.

Sub BuildArray()

'   Load array

Dim MyArr()
Dim J As Long


'   Size array

MyArr() = Range("TY[L3 Number]")
ReDim NewArr(LBound(MyArr) To UBound(MyArr))

'   For Loop to search for Blanks and remove from Array
'   The Lbound and UBound parameters will be defined by the size of the TY[L3 Number] field in the TY Table

J = LBound(MyArr) - 1 ' Added this recently while testing the theory that J may start at the 2nd      index in the loop, did not help

For i = LBound(MyArr) To UBound(MyArr)
   If MyArr(i) <> "" Then '   This is where I error out
        J = J + 1
        NewArr(J) = MyArr(i)
  End If
Next i
ReDim Preserve NewArr(LBound(MyArr) To J)

'   Debug Window to show results of revised array.

Dim c As Long
For c = LBound(NewArr) To UBound(NewArr)
   Debug.Print NewArr(c)
Next
   Debug.Print "End of List"

End Sub
Was it helpful?

Solution

Ranges are multidimensional arrays.. (i.e. MyArray(#,#) where the first index will be the row and the second the column.

Change

 If MyArr(i) <> "" Then 

to

 If MyArr(i,1) <> "" Then 

if your range have only one column, the second index will always be 1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top