Читать книгу Excel 2019 Power Programming with VBA - Michael Alexander, Dick Kusleika - Страница 174

Declaring dynamic arrays

Оглавление

A dynamic array doesn't have a preset number of elements. You declare a dynamic array with a blank set of parentheses.

Dim MyArray() As Integer

Before you can use a dynamic array in your code, however, you must use the ReDim statement to tell VBA how many elements are in the array. You can use a variable to assign the number of elements in an array. Often the value of the variable isn't known until the procedure is executing. For example, if the variable x contains a number, you can define the array's size by using this statement:

ReDim MyArray (1 To x)

You can use the ReDim statement any number of times, changing the array's size as often as you need. When you change an array's dimensions, the existing values are destroyed. If you want to preserve the existing values, use ReDim Preserve. Here's an example:

ReDim Preserve MyArray (1 To y)

Arrays crop up later in this chapter when we discuss looping (see the section “Looping blocks of instructions”).

Excel 2019 Power Programming with VBA

Подняться наверх