Последний элемент массива vba excel

I have some Excel code that assembles an array of file names, and then loops through and extracts some data from them. The data is not in the spreadsheet itself — it is completely assembled within VBA. New files are added each month, so the number will vary.

My problem is that code that was working is no longer working, and I’m trying to figure out a workaround. (Related: Error: Microsoft Excel has stopped working — But I didn’t change anything)

UBound finds the size of the array. But the array is not completely filled with data. How do I find the last item in the array that has something in it?

I am searching and finding answers that relate to finding the number of items on a spreadsheet, but this doesn’t really use a worksheet. IT seems like CountA might be what I want, but Excel: Find last value in an array doesn’t have an example that I can figure out to make work in my case.

In other words, I’d like to use something besides UBound in the code below, so I don’t go past the entries that have something in them.

    FName = Array("april2010.xls", "feb2010.xls", "jan2010.xls", "july2010.xls", "june2010.xls", _
            "mar2010.xls", "may2010.xls", "sep2010.xls", "..FINAL-MO-BAL-2011APRIL2011.xls", _
            "..FINAL-MO-BAL-2011AUG2011.xls", "..FINAL-MO-BAL-2011DEC2011.xls", _
            "..FINAL-MO-BAL-2011FEB2011.xls", "..FINAL-MO-BAL-2011JAN2011.xls", _
            "..FINAL-MO-BAL-2011JULY2011.xls", "..FINAL-MO-BAL-2011JUNE2011.xls", _
            "..FINAL-MO-BAL-2011MARCH2011.xls", "..FINAL-MO-BAL-2011MAY2011.xls", _
            "..FINAL-MO-BAL-2011NOV2011.xls", "..FINAL-MO-BAL-2011OCT2011.xls", _
            "..FINAL-MO-BAL-2011SEP2011.xls", FName2, FName3, FName4, FName5, FName6, _
            FName7, FName8, FName9, FName10, FName11, FName12, FName13, FName14, FName15, _
            FName16, FName17, FName18, FName19, FName20, FName21, FName22, FName23, FName24, _
            FName25, FName26, FName27, FName28, FName29, FName30, FName31, FName32, FName33, _
            FName34, FName35, FName36, FName37, FName38, , FName39, FName40, FName41, FName42, _
            FName43, FName44, FName45, FName46, FName47, FName48, FName49)

If IsArray(FName) Then
    Set BaseWks = Workbooks.Add(xlWBATWorksheet).Worksheets(1)
    WorkbookName = ThisWorkbook.Name
    rnum = 1
    For Fnum = LBound(FName) To UBound(FName)
        Set mybook = Nothing
        On Error Resume Next
        Set mybook = Workbooks.Open(Filename:=FName(Fnum), ReadOnly:=True)

        With Application
            CalcMode = .Calculation
            .Calculation = xlCalculationManual
            .ScreenUpdating = False
            .EnableEvents = False
            .CutCopyMode = False
            .DisplayAlerts = False
            .Visible = False
        End With

        On Error GoTo 0

        If Not mybook Is Nothing Then
            On Error Resume Next

Главная » Функции VBA »

28 Апрель 2011              134753 просмотров

  • Array() — позволяет автоматически создать массив нужного размера и типа и сразу загрузить в него переданные значения:
        'инициализируем переменную с типом Variant
        Dim avArr
        'присваиваем переменной значение массива
        avArr = Array("Первый элемент", "Второй элемент", "3", 4, "Последний")
        'показываем 3-ий по порядку элемент
        MsgBox avArr(2)

    Опечатки нет. avArr(2) действительно выдаст третий элемент, т.к. по умолчанию для массива нижняя граница равна нулю. И да, таким образом можно создать исключительно одномерный массив.

  • Filter() — позволяет на основе одного массива получить другой, отфильтровав в исходном массиве нужные нам элементы.
  • LBound() — возвращает информацию о нижней границе массива (то есть номере первого имеющегося в нем значения)
        Dim avArr
        avArr = Array("Первый элемент", "Второй элемент", "3", 4, "Последний")
        'показываем первый элемент
        MsgBox avArr(LBound(avArr))
  • UBound() — возвращает информацию о верхней границе массива (номер последнего имеющегося значения)
        Dim avArr
        avArr = Array("Первый элемент", "Второй элемент", "3", 4, "Последний")
        'показываем последний элемент
        MsgBox avArr(UBound(avArr))
  • Join() — возможность слить множество строк из массива строк в одну строковую переменную. В качестве разделителя по умолчанию используется пробел, можно указать свой разделитель.
        Dim avArr
        avArr = Array("Первый элемент", "Второй элемент", "3", 4, "Последний")
        'объединяем все элементы массива с разделителем "-"
        MsgBox Join(avArr, "-")
  • Split() — обратная функция, разбивающая строку на массив строк . В качестве разделителя по умолчанию используется пробел, можно указать свой разделитель.
        'инициализируем переменную с типом Variant
        'т.к. затем это будет массив
        Dim sStr
        'разбиваем указанный текст массив. Разделитель - "-"
        sStr = Split("Первый элемент-Второй элемент-3-4-Последний", "-")
        'показываем 3-ий по порядку элемент
        MsgBox sStr(2)

Статья помогла? Сделай твит, поделись ссылкой с друзьями!

Массивы в VBA Excel: одномерные, многомерные и динамические. Объявление и использование массивов. Операторы Public, Dim и ReDim. Функции Array, LBound, UBound.

Массивы – это множества однотипных элементов, имеющих одно имя и отличающиеся друг от друга индексами. Они могут быть одномерными (линейными), многомерными и динамическими. Массивы в VBA Excel, как и другие переменные, объявляются с помощью операторов Dim и Public. Для изменения размерности динамических массивов используется оператор ReDim. Массивы с заранее объявленной размерностью называют статическими.

Одномерные массивы

Объявление одномерных (линейных) статических массивов в VBA Excel:

Public Massiv1(9) As Integer

Dim Massiv2(1 To 9) As String

В первом случае публичный массив содержит 10 элементов от 0 до 9 (нижний индекс по умолчанию — 0, верхний индекс — 9), а во втором случае локальный массив содержит 9 элементов от 1 до 9.

По умолчанию VBA Excel считает в массивах нижним индексом нуль, но, при желании, можно сделать нижним индексом по умолчанию единицу, добавив в самом начале модуля объявление «Option Base 1».

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

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

‘Массив двухмерный

Public Massiv1(3, 6) As Integer

‘Массив трехмерный

Dim Massiv2(1 To 6, 1 To 8, 1 To 5) As String

‘Массив четырехмерный

Dim Massiv3(9, 9, 9, 9) As Date

Третий массив состоит из 10000 элементов — 10×10×10×10.

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

Динамические массивы в VBA Excel, в отличие от статических, объявляются без указания размерности:

Public Massiv1() As Integer

Dim Massiv2() As String

Такие массивы используются, когда заранее неизвестна размерность, которая определяется в процессе выполнения программы. Когда нужная размерность массива становится известна, она в VBA Excel переопределяется с помощью оператора ReDim:

Public Massiv1() As Integer

Dim Massiv2() As String

ReDim Massiv1(1 To 20)

ReDim Massiv2(3, 5, 4)

При переопределении размерности массива вместо верхнего индекса можно использовать переменную:

Dim Massiv1() as Variant, x As Integer

x = 20

ReDim Massiv1(1 To x)

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

С помощью оператора ReDim невозможно изменить обычный массив, объявленный с заранее заданной размерностью. Попытка переопределить размерность такого массива вызовет ошибку компиляции с сообщением: Array already dimensioned (Массив уже измерен).

При переопределении размерности динамических массивов в VBA Excel теряются значения их элементов. Чтобы сохранить значения, используйте оператор Preserve:

Dim Massiv1() As String

операторы

ReDim Massiv1(5, 2, 3)

операторы

ReDim Preserve Massiv1(5, 2, 7)

Обратите внимание!
Переопределить с оператором Preserve можно только последнюю размерность динамического массива. Это недоработка разработчиков, которая сохранилась и в VBA Excel 2016. Без оператора Preserve можно переопределить все размерности.

Максимальный размер

Размер массива – это произведение длин всех его измерений. Он представляет собой общее количество элементов, содержащихся в данный момент в массиве.

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

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

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

1. Как известно, функция Split возвращает одномерный массив подстрок, извлеченных из первоначальной строки с разделителями. Эти данные присваиваются заранее объявленному строковому (As String) одномерному динамическому массиву. Размерность устанавливается автоматически в зависимости от количества подстрок.

2. Данные в массивах обрабатываются значительно быстрее, чем в ячейках рабочего листа. Построчную обработку информации в таблице Excel можно наблюдать визуально по мерцаниям экрана, если его обновление (Application.ScreenUpdating) не отключено. Чтобы ускорить работу кода, можно значения из диапазона ячеек предварительно загрузить в динамический массив с помощью оператора присваивания (=). Размерность массива установится автоматически. После обработки данных в массиве кодом VBA полученные результаты выгружаются обратно на рабочий лист Excel. Обратите внимание, что загрузить значения в диапазон ячеек рабочего листа через оператор присваивания (=) можно только из двумерного массива.

Функции Array, LBound, UBound

Функция Array

Функция Array возвращает массив элементов типа Variant из первоначального списка элементов, перечисленных через запятую. Нумерация элементов в массиве начинается с нуля. Обратиться к элементу массива можно, указав в скобках его номер (индекс).

Sub Test1()

Dim a() As Variant

a = Array(«text», 25, «solo», 35.62, «stop»)

MsgBox a(0) & vbNewLine & a(1) & vbNewLine _

& a(2) & vbNewLine & a(3) & vbNewLine & a(4)

End Sub

Скопируйте код в модуль VBA Excel и запустите его на выполнение. Информационное сообщение MsgBox покажет значения массива, извлеченные по индексу.

Функция LBound

Функция LBound возвращает значение типа Long, равное наименьшему (нижнему) доступному индексу в указанном измерении массива.
Синтаксис:
LBound (arrayname[, dimension])

  • arrayname — это имя переменной массива, является обязательным аргументом;
  • dimension — это номер измерения массива, необязательный аргумент, по умолчанию принимает значение 1.

Наименьший индекс по-умолчанию может быть равен 0 или 1 в зависимости от настроек оператора Option Base. Нижняя граница архива, полученного с помощью функции Array, всегда равна 0.

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

Функция UBound

Функция UBound возвращает значение типа Long, равное наибольшему (верхнему) доступному индексу в указанном измерении массива.
Синтаксис:
UBound( arrayname[, dimension])

  • arrayname — это имя переменной массива, является обязательным аргументом;
  • dimension — это номер измерения массива, необязательный аргумент, по умолчанию принимает значение 1.

Функция UBound используется вместе с функцией LBound для определения размера массива.

Sub Test2()

Dim a(2 To 53) As String

MsgBox «Наименьший индекс = « & LBound(a) & _

vbNewLine & «Наибольший индекс = « & UBound(a)

End Sub

Скопируйте код в модуль VBA Excel и запустите его на выполнение. Информационное сообщение MsgBox покажет значения наименьшего и наибольшего индекса переменной массива a.

Обход массива циклом

Обход одномерного массива циклом For… Next, в котором для определения границ массива используются функции UBound и LBound:

Sub Test3()

Dim a() As Variant, i As Long

a = Array(«text», 25, «solo», 35.62, «stop»)

    For i = LBound(a) To UBound(a)

        Debug.Print «a(« & i & «) = « & a(i)

    Next

End Sub

Результат работы цикла вы увидите в окне Immediate.

Очистка (обнуление) массивов

Первый способ

Очистить любой массив, статический или динамический, без использования цикла можно с помощью оператора Erase. Термин «обнуление» можно применить только к массиву числового типа.

Dim Massiv1(4, 3) As String,  Massiv2() As Variant

операторы

‘переопределяем динамический массив

ReDim Massiv2(2, 5, 3)

операторы

‘очищаем массивы

Erase Massiv1

Erase Massiv2

Обратите внимание, что оба массива при таком способе очистки будут возвращены в исходное состояние, которое они имели сразу после объявления:

  • статический Massiv1 сохранит размерность (4, 3);
  • динамический Massiv2 не сохранит размерность ().

Второй способ

Динамический массив можно очистить (обнулить) без использования цикла с помощью оператора ReDim. Просто переопределите его с той же размерностью.

Dim Massiv() As Double

операторы

‘переопределяем массив

ReDim Massiv(5, 6, 8)

операторы

‘очищаем массив

ReDim Massiv(5, 6, 8)


Returns a Variant containing an array.

The required arglist argument is a comma-delimited list of values that are assigned to the elements of the array contained within the Variant. If no arguments are specified, an array of zero length is created.

The notation used to refer to an element of an array consists of the variable name followed by parentheses containing an index number indicating the desired element.

In the following example, the first statement creates a variable named A as a Variant. The second statement assigns an array to variable A . The last statement assigns the value contained in the second array element to another variable.

The lower bound of an array created by using the Array function is determined by the lower bound specified with the Option Base statement, unless Array is qualified with the name of the type library (for example VBA.Array). If qualified with the type-library name, Array is unaffected by Option Base.

A Variant that is not declared as an array can still contain an array. A Variant variable can contain an array of any type, except fixed-length strings and user-defined types. Although a Variant containing an array is conceptually different from an array whose elements are of type Variant, the array elements are accessed in the same way.

This example uses the Array function to return a Variant containing an array.

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

‘инициализируем переменную с типом Variant Dim avArr ‘присваиваем переменной значение массива avArr = Array(«Первый элемент», «Второй элемент», «3», 4, «Последний») ‘показываем 3-ий по порядку элемент MsgBox avArr(2)

Опечатки нет. avArr(2) действительно выдаст третий элемент, т.к. по умолчанию для массива нижняя граница равна нулю. И да, таким образом можно создать исключительно одномерный массив.

LBound() — возвращает информацию о нижней границе массива (то есть номере первого имеющегося в нем значения)

Dim avArr avArr = Array(«Первый элемент», «Второй элемент», «3», 4, «Последний») ‘показываем первый элемент MsgBox avArr(LBound(avArr))

Dim avArr avArr = Array(«Первый элемент», «Второй элемент», «3», 4, «Последний») ‘показываем последний элемент MsgBox avArr(UBound(avArr))

Dim avArr avArr = Array(«Первый элемент», «Второй элемент», «3», 4, «Последний») ‘объединяем все элементы массива с разделителем «-» MsgBox Join(avArr, «-«)

‘инициализируем переменную с типом Variant ‘т.к. затем это будет массив Dim sStr ‘разбиваем указанный текст массив. Разделитель — «-» sStr = Split(«Первый элемент-Второй элемент-3-4-Последний», «-«) ‘показываем 3-ий по порядку элемент MsgBox sStr(2)

Источник

VBA Arrays

What is VBA Arrays in Excel?

A VBA array in excel is a storage unit or a variable which can store multiple data values. These values must necessarily be of the same data type. This implies that the related values are grouped together to be stored in an array variable.

For example, a large organization which operates in several countries employs 10,000 people. To store the details of all employees, a database containing hundreds of rows and columns is created. So, either of the following actions can be performed:

  1. Create multiple variables to fetch the cell values and give them to the program.
  2. Create an array consisting of multiple related values.

The action “a” is far more complicated and time-consuming than action “b.” For this reason, we use VBA arrays.

To use an array variable, it needs to be declared or defined first. While declaring, the length of the array may or may not be included.

The purpose of using an array is to hold an entire list of items in its memory. In addition, with an array, it is not required to declare each variable to be fetched from the dataset.

Table of contents

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA Arrays (wallstreetmojo.com)

The Properties of VBA Arrays

The properties of VBA arrays are listed as follows:

  • In an array, the data of the same type are grouped together. So, creating an array is similar to creating a separate memory unit which can hold data.
  • The array to be used must correspond with the kind of dataset. For instance, if the dataset has a single row or a single column, a one-dimensional array is used. A two-dimensional array is used if the dataset has multiple rows and columnsRows And ColumnsA cell is the intersection of rows and columns. Rows and columns make the software that is called excel. The area of excel worksheet is divided into rows and columns and at any point in time, if we want to refer a particular location of this area, we need to refer a cell.read more .
  • An array can function as static or dynamic. A dynamic array can include an infinite number of rows and columns. In contrast, a static array holds a limited number of rows and columns, which are defined at the time of creation.

Note: During run time, the size of a static array cannot be modified while a dynamic array can be resized.

The Working of a VBA Array

An array works similar to the mathematical rule of a matrix. This implies that an array identifies the data by its location.

For example, if the number 20 is required in cell B3, we write the location in the code as (3, 2). The number “3” represents the row number and “2” represents the column number.

In Excel, the code of locations is known as upper bound and lower bound. By default, the locations in Excel begin from 0 and not from 1. Hence, “A1” is considered as row number 0 and not as row number 1.

Likewise, columns also begin from 0 and not from 1.

Note: In the preceding example of cell B3, Excel counts the rows and columns from 1.

If we define this array as static, it cannot hold more than the defined variables. Hence, if the user is not sure about the number of values to be memorized by an array, it is advisable to use a dynamic array.

The data is entered in the array, as shown in the following image.

Types of VBA Arrays

The VBA arrays can be categorized as follows:

  1. Static array
  2. Dynamic array
  3. One-dimensional array
  4. Two-dimensional array
  5. Multi-dimensional array

Let us consider every array one by one.

#1 Static Array

A static array has a fixed, pre-defined count of the values that can be stored in it. The code of a static array is written as follows:

#2 Dynamic Array

A dynamic array does not have a pre-defined count of values that can be stored in it. The code of a dynamic array is written as follows:

#3 One-dimensional Array

A one-dimensional array can hold data either from a single row or a single column of Excel.

A table consists of the marks obtained by 5 students of a class. The Excel data and the code of a one-dimensional array are shown as follows:

#4 Two-dimensional Array

A two-dimensional array can store values from multiple rows and columns of Excel.

A table consists of marks obtained by two students in Mathematics and Science. The Excel data and the code of a two-dimensional array are shown as follows:

#5 Multi-dimensional Array

A multi-dimensional array can store data from multiple sheets which contain several rows and columns. An array can have a maximum of 60 dimensions.

A table consists of the marks obtained by two students in Mathematics, Science, and Accountancy. The Excel data and the code of a multi-dimensional array are shown as follows:

How to use Arrays in VBA?

An array can be used in several situations. It is particularly used when there are a large number of variables to be declared and it is not feasible to define each and every variable.

Once the VBA editor opens, the code can be entered in “ThisWorkbook,” as shown in the following image.

The Procedure of Using an Array

The steps of using an array are listed as follows:

Step 1: Choose the type of array. It can be either dynamic or static.

For a dynamic array, the dimension is defined as “variant.”

For a static array, the dimension is defined as “static.”

Step 2: Define the rows and columns to be stored in the array.

Enter “1” within the brackets, as shown in the following image. This implies that the array can hold the values of two rows. This is because Excel begins counting from 0.

If rows and columns both are required, one needs to define them. So, enter “1 to 2” and “1 to 3” as arguments. The same is shown in the following image.

The argument “1 to 2” implies two rows and “1 to 3” implies three columns.

Note: In this case, Excel counts the rows and columns from 1 and not from 0.

Step 3: Enter the data as input in the array.

The data is entered in the form of (i,j), where “i” represents the row and “j” represents the column. Since the data is entered cell-wise, “a (1,1)” implies cell A1.

Hence, 30 will be entered in cell A1.

Step 4: Close the code.

Once the data for the array has been entered, the last step is to close the code. This is shown in the following image.

The Cautions Governing the use of VBA Arrays

The cautions to be observed while creating VBA arrays are listed as follows:

  • Remember that by default, Excel counts the rows and columns beginning from zero. So, if “i” is 2, it implies three rows. The same applies to the column entries (j) as well.
  • Ensure that the data entered in the array begins from (0,0), i.e., the first row and the first column.
  • Use the “ VBA REDIMVBA REDIMThe VBA Redim statement increases or decreases the storage space available to a variable or an array. If Preserve is used with this statement, a new array with a different size is created; otherwise, the current variable’s array size is changed.read more ” function to change the size of a dynamic array.
  • Use “integer” as the dimension of a two-dimensional array that accepts integer values.
  • Save the Excel file with the “.xlsm” extension otherwise, the VBA coding will not run the next time.

Frequently Asked Questions

A VBA array is capable of storing a series of data values. The condition is that all the values should be of the same data type. These values are known as the elements of an array.

For assigning values to an array, the location number of Excel is used. This number is known as the index or the subscript of an array. By default, the array index begins from zero unless an “Option Base 1” statement is entered at the beginning of the module.

With the “Option Base 1” statement, the array index begins from one.

Arrays are classified as follows:

• Static or dynamic based on whether the array size is fixed or changeable.
• One-dimensional, two-dimensional, or multi-dimensional based on the number of rows and columns of the source dataset from where values are assigned to an array.

An array is used for the following reasons:

• It helps avoid writing multiple lines of code. Since a regular variable can store a single value at a given time, each variable which is to be stored needs to be defined.
• It allows easy accessibility to the elements of the array. Every item of the array can be accessed with its row and column number which are specified while assigning values.
• It allows grouping the data of the same type. Since the related data is placed together, it simplifies working with large datasets.
• It adds the speed factor to working with Excel. Arrays make it easier to organize, retrieve, and alter data. This helps in improving productivity.

The JOIN function combines several substrings of an array and returns a string. The JOIN function is the reverse of the SPLIT function.

The syntax of the JOIN function is stated as follows:

The arguments are explained as follows:

• Sourcearray: This is a one-dimensional array consisting of substrings to be joined.
• Delimiter: This is a character that separates the substrings of the output. If this is omitted, the delimiter space is used.

Only the argument “sourcearray” is required.

The SPLIT function divides the whole string into multiple substrings. It splits on the basis of the specified delimiter. It returns a one-dimensional and zero-based array.

The syntax of the SPLIT function is stated as follows:

The arguments are explained as follows:

• Expression: This is the entire string which is to be split into substrings.
• Delimiter: This is a character like space, comma etc., that separates the substrings of the expression. If this is omitted, the space is considered as the delimiter.
• Limit: This is the number of substrings to be returned. It returns all the substrings if the limit is set at “-1.”
• Compare: This is the comparison method to be used. Either a binary (vbBinaryCompare) or textual comparison (vbTextCompare) can be performed.

Only the argument “expression” is required. The remaining arguments are optional.

Recommended Articles

This has been a guide to VBA Arrays. Here we discuss the different types of arrays, how to declare and use them. We also discussed the array in VBA examples. You can download the template from the website. You may also look at these useful Excel tools-

Источник

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

Dim myArray(9) As String 'Declaring an array that will contain up to 10 strings

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

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

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

myArray(0) = "first element"
myArray(5) = "sixth element"
myArray(9) = "last element"

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

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

Option Base 1

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

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

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

Dim mySecondArray(1 To 12) As String 'Array of 12 strings indexed from 1 to 12
Dim myThirdArray(13 To 24) As String 'Array of 12 strings indexed from 13 to 24

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

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

Dim myDynamicArray() As Strings 'Creates an Array of an unknown number of strings
ReDim myDynamicArray(5) 'This resets the array to 6 elements

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

Dim myDynamicArray(5) As String
myDynamicArray(0) = "Something I want to keep"

ReDim Preserve myDynamicArray(8) 'Expand the size to up to 9 strings
Debug.Print myDynamicArray(0) ' still prints the element

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

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

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

Синтаксис

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

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

настройки

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

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

пример

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

Sub Test
    
    Dim textArray() as String

    textArray = Split("Tech on the Net")
    'Result: {"Tech", "on", "the", "Net"}

    textArray = Split("172.23.56.4", ".")
    'Result: {"172", "23", "56", "4"}

    textArray = Split("A;B;C;D", ";")
    'Result: {"A", "B", "C", "D"}

    textArray = Split("A;B;C;D", ";", 1)
    'Result: {"A;B;C;D"}

    textArray = Split("A;B;C;D", ";", 2)
    'Result: {"A", "B;C;D"}

    textArray = Split("A;B;C;D", ";", 3)
    'Result: {"A", "B", "C;D"}

    textArray = Split("A;B;C;D", ";", 4)
    'Result: {"A", "B", "C", "D"}

    'You can iterate over the created array
    Dim counter As Long

    For counter = LBound(textArray) To UBound(textArray)
        Debug.Print textArray(counter)
    Next
 End Sub

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

Для … Далее

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

Dim items As Variant
items = Array(0, 1, 2, 3)

Dim index As Integer
For index = LBound(items) To UBound(items)
    'assumes value can be implicitly converted to a String:
    Debug.Print items(index) 
Next

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

Dim items(0 To 1, 0 To 1) As Integer
items(0, 0) = 0
items(0, 1) = 1
items(1, 0) = 2
items(1, 1) = 3

Dim outer As Integer
Dim inner As Integer
For outer = LBound(items, 1) To UBound(items, 1)
    For inner = LBound(items, 2) To UBound(items, 2)
        'assumes value can be implicitly converted to a String:
        Debug.Print items(outer, inner)
    Next
Next

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

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

Dim items As Variant
items = Array(0, 1, 2, 3)

Dim item As Variant 'must be variant
For Each item In items
    'assumes value can be implicitly converted to a String:
    Debug.Print item
Next

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

Dim items(0 To 1, 0 To 1) As Integer
items(0, 0) = 0
items(1, 0) = 1
items(0, 1) = 2
items(1, 1) = 3

Dim item As Variant 'must be Variant
For Each item In items
    'assumes value can be implicitly converted to a String:
    Debug.Print item
Next

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


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

 0
 1
 2
 3

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

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

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

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

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

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

Dim Dynamic_array As Variant
' first we set Dynamic_array as variant

For n = 1 To 100

    If IsEmpty(Dynamic_array) Then
        'isempty() will check if we need to add the first value to the array or subsequent ones
    
        ReDim Dynamic_array(0)
        'ReDim Dynamic_array(0) will resize the array to one variable only
        Dynamic_array(0) = n

    Else
        ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) + 1)
        'in the line above we resize the array from variable 0 to the UBound() = last variable, plus one effectivelly increeasing the size of the array by one
        Dynamic_array(UBound(Dynamic_array)) = n
        'attribute a value to the last variable of Dynamic_array
    End If

Next

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

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

Dim Dynamic_array As Variant
Dynamic_array = Array("first", "middle", "last")
    
ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) - 1)
' Resize Preserve while dropping the last value

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

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

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

Dim Dynamic_array As Variant

For n = 1 To 100

    If IsEmpty(Dynamic_array) Then
        ReDim Dynamic_array(0)
        Dynamic_array(0) = n
    
    ElseIf Dynamic_array(0) = "" Then
        'if first variant is empty ( = "") then give it the value of n
        Dynamic_array(0) = n
    Else
        ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) + 1)
        Dynamic_array(UBound(Dynamic_array)) = n
    End If
    If n = 40 Then
        ReDim Dynamic_array(0)
        'Resizing the array back to one variable without Preserving,
        'leaving the first value of the array empty
    End If

Next

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

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

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

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

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

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

Dim OuterArray() As Variant
Dim Names() As Variant
Dim Numbers() As Variant
'arrays are declared variant so we can access attribute any data type to its elements

Names = Array("Person1", "Person2", "Person3")
Numbers = Array("001", "002", "003")

OuterArray = Array(Names, Numbers)
'Directly giving OuterArray an array containing both Names and Numbers arrays inside

Debug.Print OuterArray(0)(1)
Debug.Print OuterArray(1)(1)
'accessing elements inside the jagged by giving the coordenades of the element

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

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

   Name -   Phone   -  Email  - Customer Number 
Person1 - 153486231 - [email protected] - 001
Person2 - 153486242 - [email protected] - 002
Person3 - 153486253 - [email protected] - 003
Person4 - 153486264 - [email protected] - 004
Person5 - 153486275 - [email protected] - 005

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

Dim Headers As Variant
' headers array with the top section of the customer data sheet
    For c = 1 To 4
        If IsEmpty(Headers) Then
            ReDim Headers(0)
            Headers(0) = Cells(1, c).Value
        Else
            ReDim Preserve Headers(0 To UBound(Headers) + 1)
            Headers(UBound(Headers)) = Cells(1, c).Value
        End If
    Next
    
Dim Customers As Variant
'Customers array will contain arrays of customer values
Dim Customer_Values As Variant
'Customer_Values will be an array of the customer in its elements (Name-Phone-Email-CustNum)
    
    For r = 2 To 6
    'iterate through the customers/rows
        For c = 1 To 4
        'iterate through the values/columns
            
            'build array containing customer values
            If IsEmpty(Customer_Values) Then
                ReDim Customer_Values(0)
                Customer_Values(0) = Cells(r, c).Value
            ElseIf Customer_Values(0) = "" Then
                Customer_Values(0) = Cells(r, c).Value
            Else
                ReDim Preserve Customer_Values(0 To UBound(Customer_Values) + 1)
                Customer_Values(UBound(Customer_Values)) = Cells(r, c).Value
            End If
        Next
        
        'add customer_values array to Customers Array
        If IsEmpty(Customers) Then
            ReDim Customers(0)
            Customers(0) = Customer_Values
        Else
            ReDim Preserve Customers(0 To UBound(Customers) + 1)
            Customers(UBound(Customers)) = Customer_Values
        End If
        
        'reset Custumer_Values to rebuild a new array if needed
        ReDim Customer_Values(0)
    Next

    Dim Main_Array(0 To 1) As Variant
    'main array will contain both the Headers and Customers
    
    Main_Array(0) = Headers
    Main_Array(1) = 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 уровня отступа, см. Ниже структуру:

Main_Array(0) - Headers - Array("Name","Phone","Email","Customer Number")
          (1) - Customers(0) - Array("Person1",153486231,"[email protected]",001)
                Customers(1) - Array("Person2",153486242,"[email protected]",002)
                ...
                Customers(4) - Array("Person5",153486275,"[email protected]",005)

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

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

For n = 0 To UBound(Main_Array(1))
    'n to iterate from fisrt to last array in Main_Array(1)
    
    For j = 0 To UBound(Main_Array(1)(n))
        'j will iterate from first to last element in each array of Main_Array(1)
        
        Debug.Print Main_Array(0)(j) & ": " & Main_Array(1)(n)(j)
        'print Main_Array(0)(j) which is the header and Main_Array(0)(n)(j) which is the element in the customer array
        'we can call the header with j as the header array has the same structure as the customer array
    Next
Next

ЗАПОМНИТЕ, чтобы отслеживать структуру вашего 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 измерений.

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

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

Dim 1D(3) as Variant

*1D - Visually*
(0)
(1)
(2)

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

Dim 2D(3,3) as Variant
'this would result in a 3x3 grid 

*2D - Visually*
(0,0) (0,1) (0,2)
(1,0) (1,1) (1,2)
(2,0) (2,1) (2,2)

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

Dim 3D(3,3,2) as Variant
'this would result in a 3x3x3 grid

*3D - Visually*
       1st layer                 2nd layer                  3rd layer
         front                     middle                     back
(0,0,0) (0,0,1) (0,0,2) ¦ (1,0,0) (1,0,1) (1,0,2) ¦ (2,0,0) (2,0,1) (2,0,2)
(0,1,0) (0,1,1) (0,1,2) ¦ (1,1,0) (1,1,1) (1,1,2) ¦ (2,1,0) (2,1,1) (2,1,2)
(0,2,0) (0,2,1) (0,2,2) ¦ (1,2,0) (1,2,1) (1,2,2) ¦ (2,2,0) (2,2,1) (2,2,2)

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


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

Создание

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

Dim Bosses As Variant
'set bosses as Variant, so we can input any data type we want

Bosses = [{"Jonh","Snow","President";"Ygritte","Wild","Vice-President"}]
'initialise a 2D array directly by filling it with information, the redult wil be a array(1,2) size 2x3 = 6 elements

Dim Employees As Variant
'initialize your Employees array as variant
'initialize and ReDim the Employee array so it is a dynamic array instead of a static one, hence treated differently by the VBA Compiler
ReDim Employees(100, 5)
'declaring an 2D array that can store 100 employees with 6 elements of information each, but starts empty
'the array size is 101 x 6 and contains 606 elements

For employee = 0 To UBound(Employees, 1)
'for each employee/row in the array, UBound for 2D arrays, which will get the last element on the array
'needs two parameters 1st the array you which to check and 2nd the dimension, in this case 1 = employee and 2 = information
    For information_e = 0 To UBound(Employees, 2)
    'for each information element/column in the array
        
        Employees(employee, information_e) = InformationNeeded ' InformationNeeded would be the data to fill the array
        'iterating the full array will allow for direct attribution of information into the element coordinates
    Next
Next

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

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

Dim TempEmp As Variant
'initialise your temp array as variant
ReDim TempEmp(UBound(Employees, 1) + 1, UBound(Employees, 2))
'ReDim/Resize Temp array as a 2D array with size UBound(Employees)+1 = (last element in Employees 1st dimension) + 1,
'the 2nd dimension remains the same as the original array. we effectively add 1 row in the Employee array

'transfer
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    For info = LBound(Employees, 2) To UBound(Employees, 2)
        'to transfer Employees into TempEmp we iterate both arrays and fill TempEmp with the corresponding element value in Employees
        TempEmp(emp, info) = Employees(emp, info)
    
    Next
Next

'fill remaining
'after the transfers the Temp array still has unused elements at the end, being that it was increased
'to fill the remaining elements iterate from the last "row" with values to the last row in the array
'in this case the last row in Temp will be the size of the Employees array rows + 1, as the last row of Employees array is already filled in the TempArray

For emp = UBound(Employees, 1) + 1 To UBound(TempEmp, 1)
    For info = LBound(TempEmp, 2) To UBound(TempEmp, 2)
        
        TempEmp(emp, info) = InformationNeeded & "NewRow"
    
    Next
Next

'erase Employees, attribute Temp array to Employees and erase Temp array
Erase Employees
Employees = TempEmp
Erase TempEmp

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

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

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

For emp = 0 To UBound(Employees)
    If Employees(emp, 0) = "Gloria" And Employees(emp, 1) = "Stephan" Then
    'if value found
        Employees(emp, 1) = "Married, Last Name Change"
        Exit For
        'don't iterate through a full array unless necessary
    End If
Next

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

'nested loop, will iterate through all elements
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    For info = LBound(Employees, 2) To UBound(Employees, 2)
        Debug.Print Employees(emp, info)
    Next
Next

'loop and coordinate, iteration through all rows and in each row accessing all columns directly
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    Debug.Print Employees(emp, 0)
    Debug.Print Employees(emp, 1)
    Debug.Print Employees(emp, 2)
    Debug.Print Employees(emp, 3)
    Debug.Print Employees(emp, 4)
    Debug.Print Employees(emp, 5)
Next

'directly accessing element with coordinates
Debug.Print Employees(5, 5)

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


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

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

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

Создание

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

Dim ThreeDArray As Variant
'initialise your ThreeDArray array as variant
ReDim ThreeDArray(1, 50, 5)
'declaring an 3D array that can store two sets of 51 employees with 6 elements of information each, but starts empty
'the array size is 2 x 51 x 6 and contains 612 elements

For building = 0 To UBound(ThreeDArray, 1)
    'for each building/set in the array
    For employee = 0 To UBound(ThreeDArray, 2)
    'for each employee/row in the array
        For information_e = 0 To UBound(ThreeDArray, 3)
        'for each information element/column in the array
            
            ThreeDArray(building, employee, information_e) = InformationNeeded ' InformationNeeded would be the data to fill the array
        'iterating the full array will allow for direct attribution of information into the element coordinates
        Next
    Next
Next

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

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

Dim TempEmp As Variant
'initialise your temp array as variant
ReDim TempEmp(UBound(ThreeDArray, 1), UBound(ThreeDArray, 2) + 1, UBound(ThreeDArray, 3))
'ReDim/Resize Temp array as a 3D array with size UBound(ThreeDArray)+1 = (last element in Employees 2nd dimension) + 1,
'the other dimension remains the same as the original array. we effectively add 1 row in the for each set of the 3D array

'transfer
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        For info = LBound(ThreeDArray, 3) To UBound(ThreeDArray, 3)
            'to transfer ThreeDArray into TempEmp by iterating all sets in the 3D array and fill TempEmp with the corresponding element value in each set of each row
            TempEmp(building, emp, info) = ThreeDArray(building, emp, info)
        
        Next
    Next
Next

'fill remaining
'to fill the remaining elements we need to iterate from the last "row" with values to the last row in the array in each set, remember that the first empty element is the original array Ubound() plus 1
For building = LBound(TempEmp, 1) To UBound(TempEmp, 1)
    For emp = UBound(ThreeDArray, 2) + 1 To UBound(TempEmp, 2)
        For info = LBound(TempEmp, 3) To UBound(TempEmp, 3)
            
            TempEmp(building, emp, info) = InformationNeeded & "NewRow"
        
        Next
    Next
Next

'erase Employees, attribute Temp array to Employees and erase Temp array
Erase ThreeDArray
ThreeDArray = TempEmp
Erase TempEmp

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

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

Do
' using Do ... While for early exit
    For building = 0 To UBound(ThreeDArray, 1)
        For emp = 0 To UBound(ThreeDArray, 2)
            If ThreeDArray(building, emp, 0) = "Gloria" And ThreeDArray(building, emp, 1) = "Stephan" Then
            'if value found
                ThreeDArray(building, emp, 1) = "Married, Last Name Change"
                Exit Do
                'don't iterate through all the array unless necessary
            End If
        Next
    Next
Loop While False

'nested loop, will iterate through all elements
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        For info = LBound(ThreeDArray, 3) To UBound(ThreeDArray, 3)
            Debug.Print ThreeDArray(building, emp, info)
        Next
    Next
Next

'loop and coordinate, will iterate through all set of rows and ask for the row plus the value we choose for the columns
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        Debug.Print ThreeDArray(building, emp, 0)
        Debug.Print ThreeDArray(building, emp, 1)
        Debug.Print ThreeDArray(building, emp, 2)
        Debug.Print ThreeDArray(building, emp, 3)
        Debug.Print ThreeDArray(building, emp, 4)
        Debug.Print ThreeDArray(building, emp, 5)
    Next
Next

'directly accessing element with coordinates
Debug.Print Employees(0, 5, 5)

Понравилась статья? Поделить с друзьями:
  • Последняя строка в файле excel
  • Последний столбец диапазона excel
  • Последняя строка в excel как попасть
  • Последний столбец в word
  • Последняя строка excel delphi