Как создать массив в vba
Перейти к содержимому

Как создать массив в vba

  • автор:

# Arrays

As the name indicates, multi dimensional arrays are arrays that contain more than one dimension, usually two or three but it can have up to 32 dimensions.

A multi array works like a matrix with various levels, take in example a comparison between one, two, and three Dimensions.

One Dimension is your typical array, it looks like a list of elements.

Two Dimensions would look like a Sudoku Grid or an Excel sheet, when initializing the array you would define how many rows and columns the array would have.

Three Dimensions would start to look like Rubik’s Cube, when initializing the array you would define rows and columns and layers/depths the array would have.

Further dimensions could be thought as the multiplication of the 3D, so a 4D(1,3,3,3) would be two side-by-side 3D arrays.

# Two-Dimension Array

Creating

The example below will be a compilation of a list of employees, each employee will have a set of information on the list (First Name, Surname, Address, Email, Phone . ), the example will essentially be storing on the array (employee,information) being the (0,0) is the first employee’s first name.

Resizing

Resizing or ReDim Preserve a Multi-Array like the norm for a One-Dimension array would get an error, instead the information needs to be transferred into a Temporary array with the same size as the original plus the number of row/columns to add. In the example below we’ll see how to initialize a Temp Array, transfer the information over from the original array, fill the remaining empty elements, and replace the temp array by the original array.

Changing Element Values

To change/alter the values in a certain element can be done by simply calling the coordinate to change and giving it a new value: Employees(0, 0) = "NewValue"

Alternatively iterate through the coordinates use conditions to match values corresponding to the parameters needed:

Reading

Accessing the elements in the array can be done with a Nested Loop (iterating every element), Loop and Coordinate (iterate Rows and accessing columns directly), or accessing directly with both coordinates.

Remember, it’s always handy to keep an array map when using Multidimensional arrays, they can easily become confusion.

# Three-Dimension Array

For the 3D array, we’ll use the same premise as the 2D array, with the addition of not only storing the Employee and Information but as well Building they work in.

The 3D array will have the Employees (can be thought of as Rows), the Information (Columns), and Building that can be thought of as different sheets on an excel document, they have the same size between them, but every sheets has a different set of information in its cells/elements. The 3D array will contain n number of 2D arrays.

Creating

A 3D array needs 3 coordinates to be initialized Dim 3Darray(2,5,5) As Variant the first coordinate on the array will be the number of Building/Sheets (different sets of rows and columns), second coordinate will define Rows and third Columns. The Dim above will result in a 3D array with 108 elements ( 3*6*6 ), effectively having 3 different sets of 2D arrays.

Resizing

Resizing a 3D array is similar to resizing a 2D, first create a Temporary array with the same size of the original adding one in the coordinate of the parameter to increase, the first coordinate will increase the number of sets in the array, the second and third coordinates will increase the number of Rows or Columns in each set.

The example below increases the number of Rows in each set by one, and fills those recently added elements with new information.

Changing Element Values and Reading

Reading and changing the elements on the 3D array can be done similarly to the way we do the 2D array, just adjust for the extra level in the loops and coordinates.

# Dynamic Arrays (Array Resizing and Dynamic Handling)

# Dynamic Arrays

Adding and reducing variables on an array dynamically is a huge advantage for when the information you are treating does not have a set number of variables.

# Adding Values Dynamically

You can simply resize the Array with the ReDim Statement, this will resize the array but to if you which to retain the information already stored in the array you’ll need the part Preserve .

In the example below we create an array and increase it by one more variable in each iteration while preserving the values already in the array.

# Removing Values Dynamically

We can utilise the same logic to to decrease the the array. In the example the value "last" will be removed from the array.

# Resetting an Array and Reusing Dynamically

We can as well re-utilise the arrays we create as not to have many on memory, which would make the run time slower. This is useful for arrays of various sizes. One snippet you could use to re-utilise the array is to ReDim the array back to (0) , attribute one variable to to the array and freely increase the array again.

In the snippet below I construct an array with the values 1 to 40, empty the array, and refill the array with values 40 to 100, all this done dynamically.

# Jagged Arrays (Arrays of Arrays)

# Jagged Arrays NOT Multidimensional Arrays

Arrays of Arrays(Jagged Arrays) are not the same as Multidimensional Arrays if you think about them visually Multidimensional Arrays would look like Matrices (Rectangular) with defined number of elements on their dimensions(inside arrays), while Jagged array would be like a yearly calendar with the inside arrays having different number of elements, like days in on different months.

Although Jagged Arrays are quite messy and tricky to use due to their nested levels and don’t have much type safety, but they are very flexible, allow you to manipulate different types of data quite easily, and don’t need to contain unused or empty elements.

# Creating a Jagged Array

In the below example we will initialise a jagged array containing two arrays one for Names and another for Numbers, and then accessing one element of each

# Dynamically Creating and Reading Jagged Arrays

We can as well be more dynamic in our approx to construct the arrays, imagine that we have a customer data sheet in excel and we want to construct an array to output the customer details.

We will Dynamically construct an Header array and a Customers array, the Header will contain the column titles and the Customers array will contain the information of each customer/row as arrays.

To better understand the way to Dynamically construct a one dimensional array please check Dynamic Arrays (Array Resizing and Dynamic Handling) on the Arrays documentation.

The Result of the above snippet is an Jagged Array with two arrays one of those arrays with 4 elements, 2 indention levels, and the other being itself another Jagged Array containing 5 arrays of 4 elements each and 3 indention levels, see below the structure:

To access the information you’ll have to bear in mind the structure of the Jagged Array you create, in the above example you can see that the Main Array contains an Array of Headers and an Array of Arrays ( Customers ) hence with different ways of accessing the elements.

Now we’ll read the information of the Main Array and print out each of the Customers information as Info Type: Info .

REMEMBER to keep track of the structure of your Jagged Array, in the example above to access the Name of a customer is by accessing Main_Array -> Customers -> CustomerNumber -> Name which is three levels, to return "Person4" you’ll need the location of Customers in the Main_Array, then the Location of customer four on the Customers Jagged array and lastly the location of the element you need, in this case Main_Array(1)(3)(0) which is Main_Array(Customers)(CustomerNumber)(Name) .

# Declaring an Array in VBA

Declaring an array is very similar to declaring a variable, except you need to declare the dimension of the Array right after its name:

By default, Arrays in VBA are indexed from ZERO, thus, the number inside the parenthesis doesn’t refer to the size of the array, but rather to the index of the last element

# Accessing Elements

Accessing an element of the Array is done by using the name of the Array, followed by the index of the element, inside parenthesis:

# Array Indexing

You can change Arrays indexing by placing this line at the top of a module:

With this line, all Arrays declared in the module will be indexed from ONE.

# Specific Index

You can also declare each Array with its own index by using the To keyword, and the lower and upper bound (= index):

# Dynamic Declaration

When you do not know the size of your Array prior to its declaration, you can use the dynamic declaration, and the ReDim keyword:

Note that using the ReDim keyword will wipe out any previous content of your Array. To prevent this, you can use the Preserve keyword after ReDim :

# Use of Split to create an array from a string

Split Function

returns a zero-based, one dimensional array containing a specified number of substrings.

Syntax

Split(expression [, delimiter [, limit [, compare]]])

Part Description
expression Required. String expression containing substrings and delimiters. If expression is a zero-length string("" or vbNullString), Split returns an empty array containing no elements and no data. In this case, the returned array will have a LBound of 0 and a UBound of -1.
delimiter Optional. String character used to identify substring limits. If omitted, the space character (" ") is assumed to be the delimiter. If delimiter is a zero-length string, a single-element array containing the entire expression string is returned.
limit Optional. Number of substrings to be returned; -1 indicates that all substrings are returned.
compare Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values.

Settings

The compare argument can have the following values:

Constant Value Description
Description -1 Performs a comparison using the setting of the Option Compare statement.
vbBinaryCompare 0 Performs a binary comparison.
vbTextCompare 1 Performs a textual comparison.
vbDatabaseCompare 2 Microsoft Access only. Performs a comparison based on information in your database.

Example

In this example it is demonstrated how Split works by showing several styles. The comments will show the result set for each of the different performed Split options. Finally it is demonstrated how to loop over the returned string array.

# Iterating elements of an array

# For. Next

Using the iterator variable as the index number is the fastest way to iterate the elements of an array:

Nested loops can be used to iterate multi-dimensional arrays:

# For Each. Next

A For Each. Next loop can also be used to iterate arrays, if performance doesn’t matter:

A For Each loop will iterate all dimensions from outer to inner (the same order as the elements are laid out in memory), so there is no need for nested loops:

Note that For Each loops are best used to iterate Collection objects, if performance matters.

Name already in use

docs / docs / visual-basic / programming-guide / language-features / arrays / index.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Arrays in Visual Basic

An array is a set of values, which are termed elements, that are logically related to each other. For example, an array may consist of the number of students in each grade in a grammar school; each element of the array is the number of students in a single grade. Similarly, an array may consist of a student’s grades for a class; each element of the array is a single grade.

It is possible to use individual variables to store each of our data items. For example, if our application analyzes student grades, we can use a separate variable for each student’s grade, such as englishGrade1 , englishGrade2 , etc. This approach has three major limitations:

  • We have to know at design time exactly how many grades we have to handle.
  • Handling large numbers of grades quickly becomes unwieldy. This in turn makes an application much more likely to have serious bugs.
  • It is difficult to maintain. Each new grade that we add requires that the application be modified, recompiled, and redeployed.

By using an array, you can refer to these related values by the same name, and use a number that’s called an index or subscript to identify an individual element based on its position in the array. The indexes of an array range from 0 to one less than the total number of elements in the array. When you use Visual Basic syntax to define the size of an array, you specify its highest index, not the total number of elements in the array. You can work with the array as a unit, and the ability to iterate its elements frees you from needing to know exactly how many elements it contains at design time.

Some quick examples before explanation:

Array elements in a simple array

Let’s create an array named students to store the number of students in each grade in a grammar school. The indexes of the elements range from 0 through 6. Using this array is simpler than declaring seven variables.

The following illustration shows the students array. For each element of the array:

The index of the element represents the grade (index 0 represents kindergarten).

The value that’s contained in the element represents the number of students in that grade.

The following example contains the Visual Basic code that creates and uses the array:

The example does three things:

  • It declares a students array with seven elements. The number 6 in the array declaration indicates the last index in the array; it is one less than the number of elements in the array.
  • It assigns values to each element in the array. Array elements are accessed by using the array name and including the index of the individual element in parentheses.
  • It lists each value of the array. The example uses a For statement to access each element of the array by its index number.

The students array in the preceding example is a one-dimensional array because it uses one index. An array that uses more than one index or subscript is called multidimensional. For more information, see the rest of this article and Array Dimensions in Visual Basic.

Creating an array

You can define the size of an array in several ways:

You can specify the size when the array is declared:

You can use a New clause to supply the size of an array when it’s created:

If you have an existing array, you can redefine its size by using the ReDim statement. You can specify that the ReDim statement keeps the values that are in the array, or you can specify that it creates an empty array. The following example shows different uses of the ReDim statement to modify the size of an existing array.

For more information, see the ReDim Statement.

Storing values in an array

You can access each location in an array by using an index of type Integer . You can store and retrieve values in an array by referencing each array location by using its index enclosed in parentheses. Indexes for multidimensional arrays are separated by commas (,). You need one index for each array dimension.

The following example shows some statements that store and retrieve values in arrays.

Populating an array with array literals

By using an array literal, you can populate an array with an initial set of values at the same time that you create it. An array literal consists of a list of comma-separated values that are enclosed in braces ( <> ).

When you create an array by using an array literal, you can either supply the array type or use type inference to determine the array type. The following example shows both options.

When you use type inference, the type of the array is determined by the dominant type in the list of literal values. The dominant type is the type to which all other types in the array can widen. If this unique type can’t be determined, the dominant type is the unique type to which all other types in the array can narrow. If neither of these unique types can be determined, the dominant type is Object . For example, if the list of values that’s supplied to the array literal contains values of type Integer , Long , and Double , the resulting array is of type Double . Because Integer and Long widen only to Double , Double is the dominant type. For more information, see Widening and Narrowing Conversions.

[!NOTE] You can use type inference only for arrays that are defined as local variables in a type member. If an explicit type definition is absent, arrays defined with array literals at the class level are of type Object[] . For more information, see Local type inference.

Note that the previous example defines values as an array of type Double even though all the array literals are of type Integer . You can create this array because the values in the array literal can widen to Double values.

You can also create and populate a multidimensional array by using nested array literals. Nested array literals must have a number of dimensions that’s consistent with the resulting array. The following example creates a two-dimensional array of integers by using nested array literals.

When using nested array literals to create and populate an array, an error occurs if the number of elements in the nested array literals don’t match. An error also occurs if you explicitly declare the array variable to have a different number of dimensions than the array literals.

Just as you can for one-dimensional arrays, you can rely on type inference when creating a multidimensional array with nested array literals. The inferred type is the dominant type for all the values in all the array literals for all nesting level. The following example creates a two-dimensional array of type Double[,] from values that are of type Integer and Double .

Iterating through an array

When you iterate through an array, you access each element in the array from the lowest index to the highest or from the highest to the lowest. Typically, use either the For. Next Statement or the For Each. Next Statement to iterate through the elements of an array. When you don’t know the upper bounds of the array, you can call the xref:System.Array.GetUpperBound%2A?displayProperty=nameWithType method to get the highest value of the index. Although the lowest index value is almost always 0, you can call the xref:System.Array.GetLowerBound%2A?displayProperty=nameWithType method to get the lowest value of the index.

The following example iterates through a one-dimensional array by using the For. Next statement.

The following example iterates through a multidimensional array by using a For. Next statement. The xref:System.Array.GetUpperBound%2A method has a parameter that specifies the dimension. GetUpperBound(0) returns the highest index of the first dimension, and GetUpperBound(1) returns the highest index of the second dimension.

The following example uses a For Each. Next Statementto iterate through a one-dimensional array and a two-dimensional array.

The size of an array is the product of the lengths of all its dimensions. It represents the total number of elements currently contained in the array. For example, the following example declares a 2-dimensional array with four elements in each dimension. As the output from the example shows, the array’s size is 16 (or (3 + 1) * (3 + 1).

[!NOTE] This discussion of array size does not apply to jagged arrays. For information on jagged arrays and determining the size of a jagged array, see the Jagged arrays section.

You can find the size of an array by using the xref:System.Array.Length%2A?displayProperty=nameWithType property. You can find the length of each dimension of a multidimensional array by using the xref:System.Array.GetLength%2A?displayProperty=nameWithType method.

You can resize an array variable by assigning a new array object to it or by using the ReDim statement. The following example uses the ReDim statement to change a 100-element array to a 51-element array.

There are several things to keep in mind when dealing with the size of an array.

Notes
Dimension Length The index of each dimension is 0-based, which means it ranges from 0 to its upper bound. Therefore, the length of a given dimension is one greater than the declared upper bound of that dimension.
Length Limits The length of every dimension of an array is limited to the maximum value of the Integer data type, which is xref:System.Int32.MaxValue?displayProperty=nameWithType or (2 ^ 31) — 1. However, the total size of an array is also limited by the memory available on your system. If you attempt to initialize an array that exceeds the amount of available memory, the runtime throws an xref:System.OutOfMemoryException.
Size and Element Size An array’s size is independent of the data type of its elements. The size always represents the total number of elements, not the number of bytes that they consume in memory.
Memory Consumption It is not safe to make any assumptions regarding how an array is stored in memory. Storage varies on platforms of different data widths, so the same array can consume more memory on a 64-bit system than on a 32-bit system. Depending on system configuration when you initialize an array, the common language runtime (CLR) can assign storage either to pack elements as close together as possible, or to align them all on natural hardware boundaries. Also, an array requires a storage overhead for its control information, and this overhead increases with each added dimension.

Every array has a data type, which differs from the data type of its elements. There is no single data type for all arrays. Instead, the data type of an array is determined by the number of dimensions, or rank, of the array, and the data type of the elements in the array. Two array variables are of the same data type only when they have the same rank and their elements have the same data type. The lengths of the dimensions of an array do not influence the array data type.

Every array inherits from the xref:System.Array?displayProperty=nameWithType class, and you can declare a variable to be of type Array , but you cannot create an array of type Array . For example, although the following code declares the arr variable to be of type Array and calls the xref:System.Array.CreateInstance%2A?displayProperty=nameWithType method to instantiate the array, the array’s type proves to be Object[].

Also, the ReDim Statement cannot operate on a variable declared as type Array . For these reasons, and for type safety, it is advisable to declare every array as a specific type.

You can find out the data type of either an array or its elements in several ways.

  • You can call the xref:System.Object.GetType%2A method on the variable to get a xref:System.Type object that represents the run-time type of the variable. The xref:System.Type object holds extensive information in its properties and methods.
  • You can pass the variable to the xref:Microsoft.VisualBasic.Information.TypeName%2A function to get a String with the name of run-time type.

The following example calls the both the GetType method and the TypeName function to determine the type of an array. The array type is Byte(,) . Note that the xref:System.Type.BaseType%2A?displayProperty=nameWithType property also indicates that the base type of the byte array is the xref:System.Array class.

Arrays as return values and parameters

To return an array from a Function procedure, specify the array data type and the number of dimensions as the return type of the Function Statement. Within the function, declare a local array variable with same data type and number of dimensions. In the Return Statement, include the local array variable without parentheses.

To specify an array as a parameter to a Sub or Function procedure, define the parameter as an array with a specified data type and number of dimensions. In the call to the procedure, pass an array variable with the same data type and number of dimensions.

In the following example, the GetNumbers function returns an Integer() , a one-dimensional array of type Integer . The ShowNumbers procedure accepts an Integer() argument.

In the following example, the GetNumbersMultiDim function returns an Integer(,) , a two-dimensional array of type Integer . The ShowNumbersMultiDim procedure accepts an Integer(,) argument.

Sometimes the data structure in your application is two-dimensional but not rectangular. For example, you might use an array to store data about the high temperature of each day of the month. The first dimension of the array represents the month, but the second dimension represents the number of days, and the number of days in a month is not uniform. A jagged array, which is also called an array of arrays, is designed for such scenarios. A jagged array is an array whose elements are also arrays. A jagged array and each element in a jagged array can have one or more dimensions.

The following example uses an array of months, each element of which is an array of days. The example uses a jagged array because different months have different numbers of days. The example shows how to create a jagged array, assign values to it, and retrieve and display its values.

The previous example assigns values to the jagged array on an element-by-element basis by using a For. Next loop. You can also assign values to the elements of a jagged array by using nested array literals. However, the attempt to use nested array literals (for example, Dim valuesjagged = <<1, 2>, <2, 3, 4>> ) generates compiler error BC30568. To correct the error, enclose the inner array literals in parentheses. The parentheses force the array literal expression to be evaluated, and the resulting values are used with the outer array literal, as the following example shows.

A jagged array is a one-dimensional array whose elements contain arrays. Therefore, the xref:System.Array.Length%2A?displayProperty=nameWithType property and the Array.GetLength(0) method return the number of elements in the one-dimensional array, and Array.GetLength(1) throws an xref:System.IndexOutOfRangeException because a jagged array is not multidimensional. You determine the number of elements in each subarray by retrieving the value of each subarray’s xref:System.Array.Length%2A?displayProperty=nameWithType property. The following example illustrates how to determine the number of elements in a jagged array.

Visual Basic differentiates between an uninitialized array (an array whose value is Nothing ) and a zero-length array or empty array (an array that has no elements.) An uninitialized array is one that has not been dimensioned or had any values assigned to it. For example:

A zero-length array is declared with a dimension of -1. For example:

You might need to create a zero-length array under the following circumstances:

Without risking a xref:System.NullReferenceException exception, your code must access members of the xref:System.Array class, such as xref:System.Array.Length%2A or xref:System.Array.Rank%2A, or call a Visual Basic function such as xref:Microsoft.VisualBasic.Information.UBound%2A.

You want to keep your code simple by not having to check for Nothing as a special case.

Your code interacts with an application programming interface (API) that either requires you to pass a zero-length array to one or more procedures or returns a zero-length array from one or more procedures.

Splitting an array

In some cases, you may need to split a single array into multiple arrays. This involves identifying the point or points at which the array is to be split, and then spitting the array into two or more separate arrays.

[!NOTE] This section does not discuss splitting a single string into a string array based on some delimiter. For information on splitting a string, see the xref:System.String.Split%2A?displayProperty=nameWithType method.

The most common criteria for splitting an array are:

The number of elements in the array. For example, you might want to split an array of more than a specified number of elements into a number of approximately equal parts. For this purpose, you can use the value returned by either the xref:System.Array.Length%2A?displayProperty=nameWithType or xref:System.Array.GetLength%2A?displayProperty=nameWithType method.

The value of an element, which serves as a delimiter that indicates where the array should be split. You can search for a specific value by calling the xref:System.Array.FindIndex%2A?displayProperty=nameWithType and xref:System.Array.FindLastIndex%2A?displayProperty=nameWithType methods.

Once you’ve determined the index or indexes at which the array should be split, you can then create the individual arrays by calling the xref:System.Array.Copy%2A?displayProperty=nameWithType method.

The following example splits an array into two arrays of approximately equal size. (If the total number of array elements is odd, the first array has one more element than the second.)

The following example splits a string array into two arrays based on the presence of an element whose value is «zzz», which serves as the array delimiter. The new arrays do not include the element that contains the delimiter.

You can also combine a number of arrays into a single larger array. To do this, you also use the xref:System.Array.Copy%2A?displayProperty=nameWithType method.

[!NOTE] This section does not discuss joining a string array into a single string. For information on joining a string array, see the xref:System.String.Join%2A?displayProperty=nameWithType method.

Before copying the elements of each array into the new array, you must first ensure that you have initialized the array so that it is large enough to accommodate the new array. You can do this in one of two ways:

  • Use the ReDim Preserve statement to dynamically expand the array before adding new elements to it. This is the easiest technique, but it can result in performance degradation and excessive memory consumption when you are copying large arrays.
  • Calculate the total number of elements needed for the new large array, then add the elements of each source array to it.

The following example uses the second approach to add four arrays with ten elements each to a single array.

Since in this case the source arrays are all small, we can also dynamically expand the array as we add the elements of each new array to it. The following example does that.

Collections as an alternative to arrays

Arrays are most useful for creating and working with a fixed number of strongly typed objects. Collections provide a more flexible way to work with groups of objects. Unlike arrays, which require that you explicitly change the size of an array with the ReDim Statement, collections grow and shrink dynamically as the needs of an application change.

When you use ReDim to redimension an array, Visual Basic creates a new array and releases the previous one. This takes execution time. Therefore, if the number of items you are working with changes frequently, or you cannot predict the maximum number of items you need, you’ll usually obtain better performance by using a collection.

For some collections, you can assign a key to any object that you put into the collection so that you can quickly retrieve the object by using the key.

VBA
Массивы

Объявление массива очень похоже на объявление переменной, за исключением того, что вам нужно объявить размер массива сразу после его имени:

По умолчанию массивы в VBA индексируются из ZERO , поэтому число внутри скобки не относится к размеру массива, а скорее к индексу последнего элемента

Доступ к элементам

Доступ к элементу массива осуществляется с использованием имени массива, за которым следует индекс элемента, внутри скобки:

Индексирование массива

Вы можете изменить индексирование массивов, разместив эту строку в верхней части модуля:

С этой строкой все объявленные в модуле массивы будут проиндексированы с ONE .

Специфический указатель

Вы также можете объявить каждый массив своим собственным индексом, используя ключевое слово To , а нижнюю и верхнюю границы (= индекс):

Динамическая декларация

Когда вы не знаете размер своего массива до его объявления, вы можете использовать динамическое объявление и ключевое слово ReDim :

Обратите внимание, что использование ключевого слова ReDim уничтожит любое предыдущее содержимое вашего массива. Чтобы предотвратить это, вы можете использовать ключевое слово Preserve после ReDim :

Использование Split для создания массива из строки

Функция разделения

возвращает одномерный массив на основе нуля, содержащий указанное количество подстрок.

Синтаксис

Split (выражение [, разделитель [, limit [, compare ]]] )

Часть Описание
выражение Необходимые. Строковое выражение, содержащее подстроки и разделители. Если выражение представляет собой строку нулевой длины ("" или vbNullString), Split возвращает пустой массив, не содержащий элементов и данных. В этом случае возвращаемый массив будет иметь LBound 0 и UBound -1.
ограничитель Необязательный. Строковый символ, используемый для определения пределов подстроки. Если опустить, символ пробела ("") считается разделителем. Если разделителем является строка с нулевой длиной, возвращается одноэлементный массив, содержащий всю строку выражения .
предел Необязательный. Количество подстрок, подлежащих возврату; -1 указывает, что все подстроки возвращаются.
сравнить Необязательный. Числовое значение, указывающее, какое сравнение следует использовать при оценке подстрок. См. Раздел «Настройки» для значений.

настройки

Аргумент сравнения может иметь следующие значения:

постоянная Значение Описание
Описание -1 Выполняет сравнение, используя настройку оператора сравнения параметров .
vbBinaryCompare 0 Выполняет двоичное сравнение.
vbTextCompare 1 Выполняет текстовое сравнение.
vbDatabaseCompare 2 Только Microsoft Access. Выполняет сравнение, основанное на информации в вашей базе данных.

пример

В этом примере показано, как Split работает, показывая несколько стилей. В комментариях будет отображаться результирующий набор для каждого из разных вариантов Split. Наконец, показано, как перебирать возвращаемый массив строк.

Итерирующие элементы массива

Для . Далее

Использование переменной итератора в качестве номера индекса является самым быстрым способом для итерации элементов массива:

Вложенные циклы могут использоваться для итерации многомерных массивов:

Для каждого . Далее

A For Each. Next цикл также может использоваться для повторения массивов, если производительность не имеет значения:

A For Each цикла будут выполняться итерация всех измерений от внешнего к внутреннему (в том же порядке, что и элементы, выделенные в памяти), поэтому нет необходимости в вложенных циклах:

Обратите внимание, что For Each петли лучше всего использовать для итерации объектов Collection , если имеет значение производительность.

Все 4 фрагмента выше дают одинаковый результат:

Динамические массивы (изменение размера массива и динамическая обработка)

Динамические массивы

Добавление и уменьшение переменных в массиве динамически является огромным преимуществом, когда информация, которую вы обрабатываете, не имеет определенного количества переменных.

Добавление значений динамически

Вы можете просто изменить размер массива с помощью ReDim , это изменит размер массива, но если вы сохраните информацию, уже сохраненную в массиве, вам понадобится часть Preserve .

В приведенном ниже примере мы создаем массив и увеличиваем его на еще одну переменную в каждой итерации, сохраняя значения уже в массиве.

Удаление значений динамически

Мы можем использовать ту же логику для уменьшения массива. В этом примере значение «последний» будет удалено из массива.

Сброс массива и повторное использование динамически

Мы также можем повторно использовать массивы, которые мы создаем, чтобы не иметь много памяти, что замедлит работу. Это полезно для массивов разных размеров. Один фрагмент кода можно использовать повторно использовать массив в ReDim массив обратно (0) , приписывать одной переменной в массив и снова свободно увеличивать массив.

В нижеприведенном фрагменте я создаю массив со значениями от 1 до 40, пуст массив и пополняем массив значениями от 40 до 100, все это выполняется динамически.

Жесткие массивы (массивы массивов)

Ядра массивов НЕ многомерные массивы

Массивы массивов (Jagged Arrays) не совпадают с многомерными массивами, если вы думаете о них визуально. Многомерные массивы будут выглядеть как Matrices (Rectangular) с определенным количеством элементов по их размерам (внутри массивов), в то время как массив Jagged будет похож на ежегодный календарь с внутренними массивами, имеющими различное количество элементов, например, дни в разные месяцы.

Хотя Jagged Arrays довольно беспорядочны и сложны в использовании из-за их вложенных уровней и не имеют большой безопасности типов, но они очень гибкие, позволяют вам легко манипулировать различными типами данных и не нужно содержать неиспользуемые или пустые элементы.

Создание поврежденного массива

В приведенном ниже примере мы инициализируем зубчатый массив, содержащий два массива один для имен, а другой для чисел, а затем доступ к одному элементу каждого из них

Динамическое создание и чтение массивов с зубцами

Мы также можем быть более динамичными в нашем приближении, чтобы построить массивы, представьте, что у нас есть личный лист данных клиентов в excel, и мы хотим построить массив для вывода информации о клиенте.

Мы будем динамически строить массив заголовков и массив Customers, заголовок будет содержать заголовки столбцов, а массив Customers будет содержать информацию каждого клиента / строки в виде массивов.

To better understand the way to Dynamically construct a one dimensional array please check Dynamic Arrays (Array Resizing and Dynamic Handling) on the Arrays documentation.

Результатом приведенного выше фрагмента является массив с чередованием с двумя массивами, один из тех массивов с 4 элементами, 2 уровня отступа, а другой сам по себе является другим массивом Jagged, содержащим 5 массивов из 4 элементов каждый и 3 уровня отступа, см. Ниже структуру:

Чтобы получить доступ к информации, которую вы должны иметь в виду о структуре созданного массива Jagged Array, в приведенном выше примере вы можете видеть, что Main Array содержит массив Headers и массив массивов ( Customers ), следовательно, с различными способами доступ к элементам.

Теперь мы прочитаем информацию о Main Array и распечатаем каждую из данных Клиентов в виде Info Type: Info .

ЗАПОМНИТЕ, чтобы отслеживать структуру вашего Jagged Array, в приведенном выше примере для доступа к имени клиента, Main_Array -> Customers -> CustomerNumber -> Name к Main_Array -> Customers -> CustomerNumber -> Name который состоит из трех уровней, для возврата "Person4" вам понадобится расположение клиентов в Main_Array, затем местоположение клиента 4 в массиве Jagged Customers и, наконец, местоположение Main_Array(1)(3)(0) элемента в этом случае Main_Array(1)(3)(0) который является Main_Array(Customers)(CustomerNumber)(Name) .

Многомерные массивы

Многомерные массивы

Как видно из названия, многомерные массивы представляют собой массивы, которые содержат более одного измерения, обычно два или три, но могут иметь до 32 измерений.

Массив массива работает как матрица с различными уровнями, например, сравнение между одним, двумя и тремя измерениями.

Одно измерение — ваш типичный массив, он выглядит как список элементов.

Два измерения будут выглядеть как сетка Sudoku или лист Excel, при инициализации массива вы определяете, сколько строк и столбцов будет иметь массив.

Три измерения начнут выглядеть как кубик Рубика, при инициализации массива вы будете определять строки и столбцы, а также уровни / глубины, которые будет иметь массив.

Дальнейшие измерения можно рассматривать как умножение 3D, поэтому 4D (1,3,3,3) будет представлять собой два боковых боковых 3D-массива.

Двухмерный массив

Создание

Пример ниже будет компиляцией списка сотрудников, каждый сотрудник будет иметь набор информации в списке (имя, фамилия, адрес, электронная почта, телефон . ), пример, по существу, будет храниться в массиве ( сотрудник, информация), являющееся (0,0), является первым именем первого сотрудника.

Изменение размера

Изменение размера или ReDim Preserve Multi-Array, как и норма для массива One-Dimension, приведет к ошибке, вместо этого информация должна быть перенесена в массив Temporary с тем же размером, что и оригинал, плюс число добавляемых строк / столбцов. В приведенном ниже примере мы увидим, как инициализировать Temp Array, передать информацию из исходного массива, заполнить оставшиеся пустые элементы и заменить массив temp на исходный массив.

Изменение значений элементов

Изменение / изменение значений в определенном элементе может быть выполнено путем простого вызова координаты для изменения и предоставления ей нового значения: Employees(0, 0) = "NewValue"

В качестве альтернативы, итерация по координатам использует условия для соответствия значениям, соответствующим требуемым параметрам:

чтение

Доступ к элементам в массиве может выполняться с помощью вложенного цикла (итерация каждого элемента), цикла и координат (итерации строк и доступа к столбцам напрямую) или прямого доступа к обеим координатам.

Помните , всегда удобно хранить карту массива при использовании многомерных массивов, они могут легко стать путаницей.

Трехмерный массив

Для 3D-массива мы будем использовать ту же предпосылку, что и 2D-массив, с добавлением не только хранения Employee и Information, но и построения, в котором они работают.

В трехмерном массиве будут присутствовать сотрудники (могут рассматриваться как строки), информация (столбцы) и здание, которые можно рассматривать как разные листы на документе excel, они имеют одинаковый размер между ними, но каждый лист имеет различный набор информации в своих ячейках / элементах. 3D-массив будет содержать n число 2D-массивов.

Создание

3D-массив нуждается в трех координатах для инициализации Dim 3Darray(2,5,5) As Variant первой координатой массива будет количество строений / таблиц (разные наборы строк и столбцов), вторая координата будет определять строки и третью Столбцы. В результате Dim выше будет создан трехмерный массив с 108 элементами ( 3*6*6 ), эффективно имеющий 3 разных набора 2D-массивов.

Изменение размера

Изменение размера 3D-массива аналогично изменению размера 2D, сначала создайте временный массив с тем же размером оригинала, добавляя его в координату параметра для увеличения, первая координата увеличит количество наборов в массиве, второе и третьи координаты увеличат количество строк или столбцов в каждом наборе.

Пример ниже увеличивает количество строк в каждом наборе на единицу и заполняет те недавно добавленные элементы новой информацией.

Изменение значений элементов и чтение

Чтение и изменение элементов в 3D-массиве может быть выполнено аналогично тому, как мы делаем 2D-массив, просто отрегулируйте дополнительный уровень в петлях и координатах.

Все про массивы в VBA

VBA Arrays

В таблице ниже краткая справка по использованию массивов в VBA. В статье постарался замахнуться на звание самого подробного руководства, которое вы найдете о массивах VBA.

Краткое руководство по массивам VBA

Задача Статический
массив
Динамический
массив
Объявление Dim arr(0 To 5) As
Long
Dim arr() As Long
Dim arr As Variant
Установить размер Dim arr(0 To 5) As
Long
ReDim arr(0 To 5)As
Variant
Увеличить размер
(сохранить
существующие
данные)
Только
динамический
ReDim Preserve arr(0 To 6)
Установить
значения
arr(1) = 22 arr(1) = 22
Получить значения total = arr(1) total = arr(1)
Первая позиция LBound(arr) LBound(arr)
Последняя позиция Ubound(arr) Ubound(arr)
Читать все записи (1D) For i = LBound(arr) To UBound(arr)
Next i
Or
For i = LBound(arr,1) To UBound(arr,1)
Next i
For i = LBound(arr) To UBound(arr)
Next i
Or
For i = LBound(arr,1) To UBound(arr,1)
Next i
Читать все записи (2D) For i = LBound(arr,1) To UBound(arr,1)
For j = LBound(arr,2) To UBound(arr,2)
Next j
Next i
For i = LBound(arr,1) To UBound(arr,1)
For j = LBound(arr,2) To UBound(arr,2)
Next j
Next i
Читать все записи Dim item As Variant
For Each item In arr
Next item
Dim item As Variant
For Each item In arr
Next item
Перейти на Sub Sub MySub(ByRef arr() As String) Sub MySub(ByRef arr() As String)
Возврат из функции Function GetArray()
As Long()
Dim arr(0 To 5) As
Long
GetArray = arr
End Function
Function GetArray()
As Long()
Dim arr() As Long
GetArray = arr
End Function
Получить от
функции
Только
динамический
Dim arr() As Long
Arr = GetArray()
Стереть массив Erase arr
*Сбрасывает все
значения по
умолчанию
Erase arr
*Удаляет массив
Строка в массив Только
динамический
Dim arr As Variant
arr = Split(«James:Earl:Jones»,»:»)
Массив в строку Dim sName As String
sName = Join(arr, «:»)
Dim sName As String
sName = Join(arr, «:»)
Заполните
значениями
Только
динамический
Dim arr As Variant
arr = Array(«John», «Hazel», «Fred»)
Диапазон в массив Только
динамический
Dim arr As Variant
arr = Range(«A1:D2»)
Массив в диапазон Так же, как в
динамическом
Dim arr As Variant
Range(«A5:D6») = arr

Введение

В этой статье подробно рассматриваются массивы на языке программирования Excel VBA. Она охватывает важные моменты, такие как:

  • Зачем вам массивы
  • Когда вы должны их использовать
  • Два типа массивов
  • Использование более одного измерения
  • Объявление массивов
  • Добавление значений
  • Просмотр всех предметов
  • Супер эффективный способ чтения Range в массив

В первом разделе мы рассмотрим, что такое массивы и зачем они нужны. Вы можете не понимать часть кода в первом разделе. Это нормально. Я буду разбивать на простые термины в следующих разделах статьи.

Быстрые заметки

Иногда коллекции лучше, чем массивы. Вы можете прочитать о коллекциях здесь.

Массивы и циклы идут рука об руку. Наиболее распространенными циклами, которые вы используете с массивами, являются циклы For i и For Each.

Что такое массивы и зачем они нужны?

Массив VBA — это тип переменной. Используется для хранения списков данных одного типа. Примером может быть сохранение списка стран или списка итогов за неделю.

В VBA обычная переменная может хранить только одно значение за раз.

В следующем примере показана переменная, используемая для хранения оценок ученика.

Если мы хотим сохранить оценки другого ученика, нам нужно создать вторую переменную.

В следующем примере у нас есть оценки пяти студентов

VBa Arrays

Мы собираемся прочитать эти отметки и записать их в Immediate Window.

Примечание. Функция Debug.Print записывает значения в Immediate Window. Для просмотра этого окна выберите View-> Immediate Window из меню (сочетание клавиш Ctrl + G).

ImmediateWindow ImmediateSampeText

Как видите в следующем примере, мы пишем один и тот же код пять раз — по одному для каждого учащегося.

Ниже приведен вывод из примера

VBA Arrays

Проблема с использованием одной переменной для каждого учащегося заключается в том, что вам необходимо добавить код для каждого учащегося. Поэтому, если в приведенном выше примере у вас будет тысяча студентов, вам понадобится три тысячи строк кода!

К счастью, у нас есть массивы, чтобы сделать нашу жизнь проще. Массивы позволяют нам хранить список элементов данных в одной структуре.
Следующий код показывает приведенный выше пример с использованием массива.

Преимущество этого кода в том, что он будет работать для любого количества студентов. Если нам нужно изменить этот код для работы с 1000 студентами, нам нужно всего лишь изменить (от 1 до 5) на (от 1 до 1000) в декларации. В предыдущем примере нам нужно было добавить примерно пять тысяч строк кода.

Давайте проведем быстрое сравнение переменных и массивов. Сначала мы сравним процесс объявления.

Далее мы сравниваем присвоение значения

Наконец, мы смотрим на запись значений

Как видите, использование переменных и массивов очень похоже.

Важным является тот факт, что массивы используют индекс (также называемый нижним индексом) для доступа к каждому элементу. Это означает, что мы можем легко получить доступ ко всем элементам в массиве, используя цикл For.

Теперь, когда у вас есть представление о том, почему массивы полезны, давайте пройдемся по ним шаг за шагом.

Типы массивов VBA

В VBA есть два типа массивов:

  1. Статический — массив фиксированного размера.
  2. Динамический — массив, в котором размер задается во время выполнения

Разница между этими массивами в основном в том, как они создаются. Доступ к значениям в обоих типах массивов абсолютно одинаков. В следующих разделах мы рассмотрим оба типа.

Объявление массива

Статический массив объявляется следующим образом

VBA Arrays

Как видите, размер указывается при объявлении статического массива. Проблема в том, что вы никогда не можете быть заранее уверены, какой размер вам нужен. Каждый раз, когда вы запускаете макрос, у вас могут быть разные требования к размеру.

Если вы не используете все расположения массива, ресурсы тратятся впустую. Если вам нужно больше места, вы можете использовать ReDim, но это по сути создает новый статический массив.

Динамический массив не имеет таких проблем. Вы не указываете размер, когда объявляете. Поэтому вы можете увеличиваться и уменьшаться по мере необходимости.

Динамический массив не выделяется, пока вы не используете оператор ReDim. Преимущество в том, что вы можете подождать, пока не узнаете количество элементов, прежде чем устанавливать размер массива. Со статическим массивом вы должны указать размер заранее.

Присвоение значений массиву

Чтобы присвоить значения массиву, вы используете номер местоположения (пересечении строки и столбца). Вы присваиваете значение для обоих типов массивов одинаково.

VBA Array 2

Номер места называется индексом. Последняя строка в примере выдаст ошибку «Индекс вне диапазона», так как в примере массива нет местоположения 4.

Использование функций Array и Split

Вы можете использовать функцию Array для заполнения массива списком элементов. Вы должны объявить массив как тип Variant. Следующий код показывает, как использовать эту функцию.

Arrays VBA

Массив, созданный функцией Array, начнется с нулевого индекса, если вы не используете Option Base 1 в верхней части вашего модуля. Затем он начнется с первого индекса. В программировании, как правило, считается плохой практикой иметь ваши реальные данные в коде. Однако иногда это полезно, когда вам нужно быстро протестировать некоторый код. Функция Split используется для разделения строки на массив на основе разделителя. Разделитель — это символ, такой как запятая или пробел, который разделяет элементы.

Следующий код разделит строку на массив из трех элементов.

Arrays VBA

Функция Split обычно используется, когда вы читаете из cvs или txt-файла, разделенного запятыми, или из другого источника, который предоставляет список элементов, разделенных одним и тем же символом.

Использование циклов с массивами

Использование цикла For обеспечивает быстрый доступ ко всем элементам массива. Вот где сила использования массивов становится очевидной. Мы можем читать массивы с десятью значениями или десятью тысячами значений, используя те же несколько строк кода. В VBA есть две функции: LBound и UBound. Эти функции возвращают самый маленький и самый большой индекс в массиве. В массиве arrMarks (от 0 до 3) LBound вернет 0, а UBound вернет 3.

В следующем примере случайные числа присваиваются массиву с помощью цикла. Затем он печатает эти числа, используя второй цикл.

Функции LBound и UBound очень полезны. Их использование означает, что наши циклы будут работать правильно с любым размером массива. Реальное преимущество заключается в том, что если размер массива изменяется, нам не нужно менять код для печати значений. Цикл будет работать для массива любого размера, пока вы используете эти функции.

Использование цикла For Each

Вы можете использовать цикл For Each с массивами. Важно помнить, что он доступен только для чтения. Это означает, что вы не можете изменить значение в массиве.

В следующем коде значение метки изменяется, но оно не меняет значение в массиве.

Цикл For Each отлично подходит для чтения массива. Как видите, лучше писать специально для двумерного массива.

Использование Erase

Функция Erase может использоваться для массивов, но она работает по-разному в зависимости от типа массива.

Для статического массива функция Erase сбрасывает все значения по умолчанию. Если массив состоит из целых чисел, то все значения устанавливаются в ноль. Если массив состоит из строк, то все строки устанавливаются в «» и так далее.

Для динамического массива функция удаления стирает память. То есть она удаляет массив. Если вы хотите использовать его снова, вы должны использовать ReDim для выделения памяти.

Давайте рассмотрим пример статического массива. Этот пример аналогичен примеру ArrayLoops в последнем разделе с одним отличием — мы используем Erase после установки значений. Когда значение будет распечатано, все они будут равны нулю.

Теперь мы попробуем тот же пример с динамикой. После того, как мы используем Erase, все места в массиве были удалены. Нам нужно использовать ReDim, если мы хотим использовать массив снова.

Если мы попытаемся получить доступ к членам этого массива, мы получим ошибку «Индекс вне диапазона».

ReDim с Preserve

Если мы используем ReDim для существующего массива, то массив и его содержимое будут удалены.

В следующем примере второй оператор ReDim создаст совершенно новый массив. Исходный массив и его содержимое будут удалены.

Если мы хотим расширить размер массива без потери содержимого, мы можем использовать ключевое слово Preserve.

Когда мы используем Redim Preserve, новый массив должен начинаться с того же начального размера, например мы не можем сохранить от (0 до 2) до (от 1 до 3) или до (от 2 до 10), поскольку они являются различными начальными размерами.

В следующем коде мы создаем массив с использованием ReDim, а затем заполняем массив типами фруктов.

Затем мы используем Preserve для увеличения размера массива, чтобы не потерять оригинальное содержимое.

Из приведенных ниже снимков экрана видно, что исходное содержимое массива было «сохранено».

VBA Preserve VBA Preserve

Предостережение: в большинстве случаев вам не нужно изменять размер массива, как мы делали в этом разделе. Если вы изменяете размер массива несколько раз, то вам захочется рассмотреть возможность использования коллекции.

Использование Preserve с 2-мерными массивами

Preserve работает только с верхней границей массива.

Например, если у вас есть двумерный массив, вы можете сохранить только второе измерение, как показано в следующем примере:

Если мы попытаемся использовать Preserve на нижней границе, мы получим ошибку «Индекс вне диапазона».

В следующем коде мы используем Preserve для первого измерения. Запуск этого кода приведет к ошибке «Индекс вне диапазона»:

Когда мы читаем из диапазона в массив, он автоматически создает двумерный массив, даже если у нас есть только один столбец.

Применяются те же правила сохранения. Мы можем использовать Preserve только на верхней границе, как показано в следующем примере:

Сортировка массива

В VBA нет функции для сортировки массива. Мы можем отсортировать ячейки листа, но это медленно, если данных много.

Функция быстрой сортировки ниже может использоваться для сортировки массива.

Вы можете использовать эту функцию так:

Передача массива в Sub или функцию

Иногда вам нужно будет передать массив в процедуру. Вы объявляете параметр, используя круглые скобки, аналогично тому, как вы объявляете динамический массив.

Переход к процедуре с использованием ByRef означает, что вы передаете ссылку на массив. Таким образом, если вы измените массив в процедуре, он будет изменен, когда вы вернетесь.

Примечание. Когда вы используете массив в качестве параметра, он не может использовать ByVal, он должен использовать ByRef. Вы можете передать массив с помощью ByVal, сделав параметр вариантом.

Возвращение массива из функции

Важно помнить следующее. Если вы хотите изменить существующий массив в процедуре, вы должны передать его как параметр, используя ByRef (см. Последний раздел). Вам не нужно возвращать массив из процедуры.

Основная причина возврата массива — это когда вы используете процедуру для создания нового. В этом случае вы присваиваете возвращаемый массив массиву в вызывающей программе. Этот массив не может быть уже выделен. Другими словами, вы должны использовать динамический массив, который не был выделен.

Следующие примеры показывают это:

Двумерные массивы

Массивы, на которые мы смотрели до сих пор, были одномерными. Это означает, что массивы представляют собой один список элементов.

Двумерный массив — это список списков. Если вы думаете об одной строке электронной таблицы как об одном измерении, то более одного столбца является двухмерным. На самом деле электронная таблица является эквивалентом двумерного массива. Он имеет два измерения — строки и столбцы.

Следует отметить одну маленькую вещь: Excel обрабатывает одномерный массив как строку, если вы записываете его в электронную таблицу. Другими словами, массив arr (от 1 до 5) эквивалентен arr (от 1 до 1, от 1 до 5) при записи значений в электронную таблицу.

На следующем рисунке показаны две группы данных. Первый — это одномерный массив, а второй — двухмерный.

VBA Array Dimension

Чтобы получить доступ к элементу в первом наборе данных (одномерном), все, что вам нужно сделать, это дать строку, например. 1,2, 3 или 4.

Для второго набора данных (двумерного) вам нужно указать строку И столбец. Таким образом, вы можете думать, что 1-мерное — это несколько столбцов, а одна строка и двухмерное — это несколько строк и несколько столбцов.

Примечание. В массиве может быть более двух измерений. Это редко требуется. Если вы решаете проблему с помощью 3+-мерного массива, то, вероятно, есть лучший способ сделать это.

Вы объявляете двумерный массив следующим образом:

В следующем примере создается случайное значение для каждого элемента в массиве и печатается значение в Immediate Window.

Видите, что мы используем второй цикл For внутри первого цикла, чтобы получить доступ ко всем элементам.

Результат примера выглядит следующим образом:

VBA Arrays

Этот макрос работает следующим образом:

  • Входит в цикл i
  • i установлен на 0
  • цикл Enters j
  • j установлен на 0
  • j установлен в 1
  • j установлен на 2
  • Выход из цикла j
  • i установлен в 1
  • j установлен на 0
  • j установлен в 1
  • j установлен на 2
  • И так до тех пор, пока i = 3 и j = 2

Заметьте, что LBound и UBound имеют второй аргумент 2. Это указывает, что это верхняя или нижняя граница второго измерения. Это начальное и конечное местоположение для j. Значение по умолчанию 1, поэтому нам не нужно указывать его для цикла i.

Использование цикла For Each

Использование For Each лучше использовать при чтении из массива.
Давайте возьмем код сверху, который выписывает двумерный массив.

Теперь давайте перепишем его, используя цикл For Each. Как видите, нам нужен только один цикл, и поэтому гораздо проще написать:

Использование цикла For Each дает нам массив только в одном порядке — от LBound до UBound. В большинстве случаев это все, что вам нужно.

Чтение из диапазона ячеек в массив

Если вы читали мою статью о ячейках и диапазонах, то вы знаете, что VBA имеет чрезвычайно эффективный способ чтения из диапазона ячеек в массив и наоборот.

Динамический массив, созданный в этом примере, будет двухмерным массивом. Как видите, мы можем прочитать весь диапазон ячеек в массив всего за одну строку.

В следующем примере будут считаны примеры данных студента ниже из C3: E6 Лист1 и распечатаны в Immediate Window.

VBA 2D Array VBA 2D Array Output

Как видите, первое измерение (доступное через i) массива — это строка, а второе — столбец. Чтобы продемонстрировать это, взглянем на значение 44 в Е4 данных образца. Это значение находится в строке 2 столбца 3 наших данных. Вы можете видеть, что 44 хранится в массиве в StudentMarks (2,3).

Как заставить ваши макросы работать на суперскорости

Если ваши макросы работают очень медленно, этот раздел будет очень полезным. Особенно, если вы имеете дело с большими объемами данных. В VBA это держится в секрете.

Обновление значений в массивах происходит экспоненциально быстрее, чем обновление значений в ячейках.

В последнем разделе вы увидели, как мы можем легко читать из группы ячеек в массив и наоборот. Если мы обновляем много значений, то мы можем сделать следующее

  1. Скопируйте данные из ячеек в массив.
  2. Измените данные в массиве.
  3. Скопируйте обновленные данные из массива обратно в ячейки.

Например, следующий код будет намного быстрее, чем код ниже:

Назначение из одного набора ячеек в другой также намного быстрее, чем с помощью копирования и вставки.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *