anon
anon

Reputation:

Can I Use a Variable to ReDim an Array?

I am not entirely sure why I am getting the error message of

Expecting a dynamic array var

with this code:

Option Explicit

Sub ArrayTest()
    Dim i As Integer, BankList(0) As Variant, x As Integer
    For i = 0 To UBound(ScreenArray)
        If ScreenArray(i) Like "TR=SUB*" Then
            Debug.Print ScreenArray(i)
            ReDim Preserve BankList(x)    '<<< ERROR LINE
            BankList(x) = ScreenArray(i)
            x = x + 1   'Raise the value for the next occurrence, if needed.
        End If
    Next
End Sub

Basically I am attempting to move specific strings from one array to a new array, if certain criteria are met. It's difficult to determine how many strings will be in the new array until running this For...Next statement.

If you can't tell from the code, the original array is ScreenArray and the new array is BankList.

Upvotes: 1

Views: 996

Answers (1)

YowE3K
YowE3K

Reputation: 23974

To create a dynamic array, do not specify the size in the original declaration.

So use BankList() As Variant instead of BankList(0) As Variant.

Upvotes: 5

Related Questions