Shankar Panda
Shankar Panda

Reputation: 832

Subscript out of range error in VBA?

I am trying to keep the values in the array. There is some 604 values it retrieves. This is giving me subscript out of range error. Can anyone help?

PlCounter = 1    
ReDim PlArray(1 To PlCounter)

For Each plv In fs.PickListValues
    Debug.Print "entered into loop"

    Set pl = plv

    Debug.Print pl.Value

    If Len(pl.Value) = 0 Then
        Debug.Print " The length is null ..so assigining null"

        ReDim Preserve PlArray(1 To PlCounter)

        PlArray(PlCounter) = "NULL"
        PlCounter = PlCounter + 1
    Else
        Debug.Print " The length is not null ..so assigining vlaues"

        ReDim Preserve PlArray(1 To PlCounter)

        PlArray(PlCounter) = pl.Value
        PlCounter = PlCounter + 1
    End If

    Next plv
    End If
Next v1

Debug.Print "The final value of Plcoutner is "; PlCounter
Debug.Print "The Final Value of PlArray "; PlArray(PlCounter - 1) -- This is getting out of range error

Upvotes: 0

Views: 104

Answers (2)

Brandon Barney
Brandon Barney

Reputation: 2392

If all you are trying to get out of the array is the upper-most value (as in, the value at the upper-most bound) then just use the property meant for that:

Debug.Print "The upper bound is "; Ubound(PlArray); "with a value of "; PlArray(Ubound(PlArray))

This ensures that you get the very last index of the array, regardless of how it is defined. This will also work if there is only one item in the array.

Likewise, you could use a similar operation when using Redim:

ReDim Preserve PlArray(LBound(PlArray) To UBound(PlArray) + 1)

This will help you avoid using that counter variable which will inevitably cause issues, especially since it is only being used to resize the array.

On a separate note, you may want to consider loading your range into an array in one shot. This will be faster to loop through as well (if you want to nullify what would otherwise be Empty for null cells).:

Dim Foo as Variant
Foo = SomeWorksheet.Range("A1:A100").Value

Keep in mind this will create a 2d array with a lower bound of 1 on both dimensions. So, if you need a 1d array, you must translate the items out of this array and into your 1d array.

Upvotes: 0

Xabier
Xabier

Reputation: 7735

I believe that you are trying to print PlArray(PlCounter - 1) when in fact your array goes from 1 to PlCounter, so in essence the debug print is trying to print PlArray(0) which is out of range.

You could fix this by replacing this line:

 Debug.Print "The Final Value of PlArray "; PlArray(PlCounter - 1)

With something like this:

 If PlCounter > 1 then Debug.Print "The Final Value of PlArray "; PlArray(PlCounter - 1)

Upvotes: 2

Related Questions