Программируя в VBA, часто можно столкнуться с ситуацией, когда приходится решать одни и те же задачи снова и снова из-за того, что в языке нет удобных встроенных средств для работы с объектами. В данной статье собраны аналоги функций Python для работы с объектами в VBA.
Содержание
Table of Contents:
- Функция для добавления элемента к массиву VBA
- Последняя строка/столбец VBA
- Метод 1 — UsedRange
- Метод 2 — End(xlUp).Row
- Метод 3 — пользовательская функция. Получить последнюю ячейку как объект Range
Функция для добавления элемента к массиву VBA
Аналог метода append из Python для массива MS Office VBA.
# Метод в Python
MyList.append(ItemToAppend)
Вариант аналога в VBA:
'Функция append:
Function append(InArray, Value) 'InArray - массив, Value - элемент, который необходимо добавить к нему
ReDim Preserve InArray(UBound(InArray) + 1) 'увеличиваем размер массива с сохранением имеющихся в нём значений
InArray(UBound(InArray)) = Value 'дописываем Value в массив
append = InArray 'функция возвращает новый массив
End Function
'Пример использования функции:
Sub MySub ()
'Для работы необходимо вставить эту функцию в свой проект VBA
'и использовать в качестве первого аргумента динамический массив:
ReDim InArray(0) as Variant 'Наш динамический массив
ReDim Value as String 'Произвольная переменная, например, типа String
Value = "MyStringValue" 'записываем произвольный текст в переменную
InArray = append(InArray, Value) 'вызов функции append
Debug.Print (InArray(1)) 'Убедиться в том, что первый элемент добавлен можно, например, так - в окне Immediate
MsgBox(InArray(1)) 'либо так – в сообщении
End Sub
UPD 2022. Вариант проще:
ReDim Preserve MyArray (UBound(MyArray) + 1)
MyArray (UBound(MyArray))= "VALUE"
Последняя строка/столбец VBA
Метод 1 — UsedRange
LastRow1 = ActiveSheet.UsedRange.Row + ActiveSheet.UsedRange.Rows.Count - 1
LastCol1 = ActiveSheet.UsedRange.Column + ActiveSheet.UsedRange.Columns.Count - 1
UsedRange — область на листе, в которой что-то есть. Использование отдельно UsedRange.Rows.Count для поиска последнего ряда/столбца ненадёжно, т.к. в случае, если на листе есть пустые столбцы/строки, будет получен неверный результат.
Метод 2 — End(xlUp).Row
Метод следует использовать, если нужно найти последний заполненный столбец/строку по конкретной строке/столбцу.
LastRow2 = Cells(Rows.Count, 7).End(xlUp).Row ' Найти последнюю строку в столбце 7
LastCol2 = Cells(13, Columns.Count).End(xlToLeft).Column 'Найти послдений столбец в строке 13
Метод 3 — пользовательская функция. Получить последнюю ячейку как объект Range
В данном случае используется поиск -1 значения относительно первой ячейки по столбцам и по строкам. По умолчанию работает на активном листе. Можно указать на вход лист (как объект Worksheet).
Function Last_Cell(Optional ws As Worksheet) As Range
Dim LastCol As Long, LastRow As Long
LastCol = 1
LastRow = 1
On Error Resume Next
If ws Is Nothing Then Set ws = ActiveSheet
LastCol = ws.UsedRange.Cells.Find(what:="*", after:=ws.UsedRange.Cells(1), _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, searchformat:=False).Column
LastRow = ws.UsedRange.Cells.Find(what:="*", after:=ws.UsedRange.Cells(1), _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, searchformat:=False).Row
Set Last_Cell = ws.Cells(LastRow, LastCol)
End Function
Все функции:
Скачать пример xlsm
Sub findlastrow()
'1 - using UsedRange
LastRow1 = ActiveSheet.UsedRange.Row + ActiveSheet.UsedRange.Rows.Count - 1
LastCol1 = ActiveSheet.UsedRange.Column + ActiveSheet.UsedRange.Columns.Count - 1
'where UsedRange begins + number of rows/columns in the usedrange - 1
Debug.Print ("Method 1")
Debug.Print ("Row" + Str(LastRow1) + " Column " + Str(LastCol1))
Debug.Print ("Value " + Str(ThisWorkbook.ActiveSheet.Cells(LastRow1, LastCol1).Value))
Debug.Print (" Usedrange params")
Debug.Print (" ActiveSheet.UsedRange.Rows.Count " + Str(ActiveSheet.UsedRange.Rows.Count))
Debug.Print (" ActiveSheet.UsedRange.Row " + Str(ActiveSheet.UsedRange.Row))
Debug.Print ("LastCol " + Str(LastCol1))
Debug.Print (" ")
'2 if you know which column/row to choose to count as last:
LastRow2 = Cells(Rows.Count, 7).End(xlUp).Row '!!!! 7 - column to look for last row
LastCol2 = Cells(13, Columns.Count).End(xlToLeft).Column '!!! row to look for last column
Debug.Print ("Method 2")
Debug.Print ("LastRow " + Str(LastRow2) + " LastCol " + Str(LastCol2))
Debug.Print (" ")
'3 - ultimate solution - custom function - using Search (previous from the first cell -> last cell
' output of the funciton Last_Cell - object (range) - lastcell
LastRow = Last_Cell.Row
LastCol = Last_Cell.Column
LastVal = Last_Cell.Value
Debug.Print ("Method 3")
Debug.Print ("Last_Cell.Row " + Str(Last_Cell.Row))
Debug.Print ("Last_Cell.Column " + Str(Last_Cell.Column))
Debug.Print ("Last_Cell.Value " + Str(Last_Cell.Value))
End Sub
Function Last_Cell(Optional ws As Worksheet) As Range
Dim LastCol As Long, LastRow As Long
LastCol = 1
LastRow = 1
On Error Resume Next
If ws Is Nothing Then Set ws = ActiveSheet
LastCol = ws.UsedRange.Cells.Find(what:="*", after:=ws.UsedRange.Cells(1), _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, searchformat:=False).Column
LastRow = ws.UsedRange.Cells.Find(what:="*", after:=ws.UsedRange.Cells(1), _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, searchformat:=False).Row
Set Last_Cell = ws.Cells(LastRow, LastCol)
End Function
'OUTPUT:
'Method 1
'Row 13 Column 7
'Value 1234
' Usedrange params
' ActiveSheet.UsedRange.Rows.Count 1
' ActiveSheet.UsedRange.Row 13
'LastCol 7
'Method 2
'LastRow 13 LastCol 7
'Method 3
'Last_Cell.Row 13
'Last_Cell.Column 7
'Last_Cell.Value 1234
Home / VBA / Arrays / VBA Add New Value to the Array
To add a new value to an existing array you need to have a dynamic array to redefine the elements of it, and when you do this, you need to preserve the values for the old elements. That helps you to only add the value to the new element you have defined and gives the rest of the part intact.
Below you have an array where you have two elements defined. As it’s a dynamic array you have a “ReDim” statement to define two elements and then add values to those elements.
Ahead we will add a third element to this array.
- First, you need to use the “ReDim” statement with the “Preserve” keyword to preserve the two elements including the new element for which you want to add the value.
- Next, you need to define the elements that you want to have in the array. Here you need to have three elements, so we are using 1 to 3 for that.
- After that, you need to add value to the third element which is the new element you have defined.
- In the end, use the debug.print to get all the elements along with the new elements into the immediate window.
Option Explicit
Option Base 1
Sub vba_array_add_value()
Dim myArray() As Variant
ReDim myArray(2)
myArray(1) = 5
myArray(2) = 10
ReDim Preserve myArray(1 To 3)
myArray(3) = 15
Debug.Print myArray(1)
Debug.Print myArray(2)
Debug.Print myArray(3)
End Sub
Let me share a few more words with you.
- You need to declare an array as a dynamic array at the starting if you know you need to add more value to the array in the code further.
- By using this method, you can only add a new element to the end of the array.
I would like to add a value to the end of a VBA array. How can I do this? I was not able to find a simple example online. Here’s some pseudocode showing what I would like to be able to do.
Public Function toArray(range As range)
Dim arr() As Variant
For Each a In range.Cells
'how to add dynamically the value to end and increase the array?
arr(arr.count) = a.Value 'pseudo code
Next
toArray= Join(arr, ",")
End Function
TylerH
5421 gold badge7 silver badges20 bronze badges
asked Sep 8, 2014 at 14:39
1
I solved the issue by using a Collection and copy it afterwards to an array.
Dim col As New Collection
For Each a In range.Cells
col.Add a.Value ' dynamically add value to the end
Next
Dim arr() As Variant
arr = toArray(col) 'convert collection to an array
Function toArray(col As Collection)
Dim arr() As Variant
ReDim arr(0 To col.Count-1) As Variant
For i = 1 To col.Count
arr(i-1) = col(i)
Next
toArray = arr
End Function
answered Sep 9, 2014 at 12:00
megloffmegloff
3892 gold badges4 silver badges11 bronze badges
1
Try this [EDITED]:
Dim arr() As Variant ' let brackets empty, not Dim arr(1) As Variant !
For Each a In range.Cells
' change / adjust the size of array
ReDim Preserve arr(1 To UBound(arr) + 1) As Variant
' add value on the end of the array
arr (UBound(arr)) = a.value
Next
answered Sep 8, 2014 at 14:50
Leo ChapiroLeo Chapiro
15.4k5 gold badges42 silver badges45 bronze badges
8
This is how I do it, using a Variant (array) variable:
Dim a As Range
Dim arr As Variant 'Just a Variant variable (i.e. don't pre-define it as an array)
For Each a In Range.Cells
If IsEmpty(arr) Then
arr = Array(a.value) 'Make the Variant an array with a single element
Else
ReDim Preserve arr(UBound(arr) + 1) 'Add next array element
arr(UBound(arr)) = a.value 'Assign the array element
End If
Next
Or, if you actually do need an array of Variants (to pass to a property like Shapes.Range, for example), then you can do it this way:
Dim a As Range
Dim arr() As Variant
ReDim arr(0 To 0) 'Allocate first element
For Each a In Range.Cells
arr(UBound(arr)) = a.value 'Assign the array element
ReDim Preserve arr(UBound(arr) + 1) 'Allocate next element
Next
ReDim Preserve arr(LBound(arr) To UBound(arr) - 1) 'Deallocate the last, unused element
answered Jan 15, 2015 at 23:33
1
If your range is a single vector, and, if in a column, the number of rows is less than 16,384, you can use the following code:
Option Explicit
Public Function toArray(RNG As Range)
Dim arr As Variant
arr = RNG
With WorksheetFunction
If UBound(arr, 2) > 1 Then
toArray = Join((.Index(arr, 1, 0)), ",")
Else
toArray = Join(.Transpose(.Index(arr, 0, 1)), ",")
End If
End With
End Function
answered Sep 9, 2014 at 20:08
Ron RosenfeldRon Rosenfeld
7,9213 gold badges13 silver badges16 bronze badges
Thx. Doing the same with 2 functions if it can help other noobs like me :
Collection
Function toCollection(ByVal NamedRange As String) As Collection
Dim i As Integer
Dim col As New Collection
Dim Myrange As Variant, aData As Variant
Myrange = Range(NamedRange)
For Each aData In Myrange
col.Add aData '.Value
Next
Set toCollection = col
Set col = Nothing
End Function
1D Array :
Function toArray1D(MyCollection As Collection)
' See http://superuser.com/a/809212/69050
If MyCollection Is Nothing Then
Debug.Print Chr(10) & Time & ": Collection Is Empty"
Exit Function
End If
Dim myarr() As Variant
Dim i As Integer
ReDim myarr(1 To MyCollection.Count) As Variant
For i = 1 To MyCollection.Count
myarr(i) = MyCollection(i)
Next i
toArray1D = myarr
End Function
Usage
Dim col As New Collection
Set col = toCollection(RangeName(0))
Dim arr() As Variant
arr = toArray1D(col)
Set col = Nothing
answered Oct 4, 2014 at 17:03
hornetbzzhornetbzz
2113 silver badges13 bronze badges
The answer is in the accepted response in(without the ReDim problem):
https://stackoverflow.com/questions/12663879/adding-values-to-variable-array-vba
In resume:
Dim aArray() As Single ' or whatever data type you wish to use
ReDim aArray(1 To 1) As Single
If strFirstName = "henry" Then
aArray(UBound(aArray)) = 123.45
ReDim Preserve aArray(1 To UBound(aArray) + 1) As Single
End If
answered Apr 8, 2018 at 2:00
0
Dim arr() As Variant: ReDim Preserve arr(0) ' Create dynamic array
' Append to dynamic array function
Function AppendArray(arr() As Variant, var As Variant) As Variant
ReDim Preserve arr(LBound(arr) To UBound(arr) + 1) ' Resize array, add index
arr(UBound(arr) - 1) = var ' Append to array
End Function
answered Aug 9, 2019 at 5:00
Объявление массива очень похоже на объявление переменной, за исключением того, что вам нужно объявить размер массива сразу после его имени:
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)
Dion-one 1 / 1 / 0 Регистрация: 09.06.2010 Сообщений: 11 |
||||
1 |
||||
Вставка элементов в массив29.09.2010, 20:42. Показов 6761. Ответов 4 Метки нет (Все метки)
Подскажите пожалуйста, как вставлять в массив элементы, т.е я вывел массив 3 1 2 , и после цифры один я должен вставить 3, что бы получилось 3 1 3 2 Подскажите пожалуйста!
Я как понял его нужно просто сместить впра на один индекс)) ТОк чет сделать не получаеться!) Помогите пожалуйста! Добавлено через 3 часа 11 минут
0 |
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
29.09.2010, 20:42 |
4 |
аналитика здесь больше нет… 3372 / 1670 / 184 Регистрация: 03.02.2010 Сообщений: 1,219 |
||||
29.09.2010, 21:30 |
2 |
|||
1 |
Dion-one 1 / 1 / 0 Регистрация: 09.06.2010 Сообщений: 11 |
||||||||
29.09.2010, 22:05 [ТС] |
3 |
|||||||
Блин спасибо =)
Но ваш способ проще! =) Благодарю ещо раз =) Добавлено через 4 минуты Добавлено через 23 минуты
Разобрался =)
0 |
здесь больше нет… 3372 / 1670 / 184 Регистрация: 03.02.2010 Сообщений: 1,219 |
|
29.09.2010, 22:12 |
4 |
А можно пояснить смысл вами написаннго?) Буду весьма признатален! алгоритм следующий: Изображения
1 |
1 / 1 / 0 Регистрация: 09.06.2010 Сообщений: 11 |
|
29.09.2010, 22:18 [ТС] |
5 |
аналитика, Спасибо огромное
0 |