Populating VBA dynamic arrays

前端 未结 5 1106
悲哀的现实
悲哀的现实 2020-12-07 13:19

The following code gives me error 9 \"subscript out of range\". I meant to declare a dynamic array so that the dimension changes as I add elements to it. Do I have to create

5条回答
  •  [愿得一人]
    2020-12-07 14:08

    Yes, you're looking for the ReDim statement, which dynamically allocates the required amount of space in the array.

    The following statement

    Dim MyArray()
    

    declares an array without dimensions, so the compiler doesn't know how big it is and can't store anything inside of it.

    But you can use the ReDim statement to resize the array:

    ReDim MyArray(0 To 3)
    

    And if you need to resize the array while preserving its contents, you can use the Preserve keyword along with the ReDim statement:

    ReDim Preserve MyArray(0 To 3)
    

    But do note that both ReDim and particularly ReDim Preserve have a heavy performance cost. Try to avoid doing this over and over in a loop if at all possible; your users will thank you.


    However, in the simple example shown in your question (if it's not just a throwaway sample), you don't need ReDim at all. Just declare the array with explicit dimensions:

    Dim MyArray(0 To 3)
    

提交回复
热议问题