Word vba массив строк

A Functional Approach

Using the same solution as @matan_justme and @mark_e, I think the structure can be cleaned up a bit.

Just as the built in function Array we can build our own custom function that uses a ParamArray to accept an array of items as the argument, and return a String Array.

By default, when assigning values to a String Array it will implicitly convert any non-String values into a String.

Public Function StringArray(ParamArray values() As Variant) As String()
    Dim temp() As String
    ReDim temp(LBound(values) To UBound(values))

    Dim index As Long
    For index = LBound(temp) To UBound(temp)
        temp(index) = values(index)
    Next
    StringArray = temp
End Function

Reusability of this structure

The nice thing with this structure is that it can be applied to different data types with intuitive naming conventions. For instance, if we need an Array with Long values, we simply need to change every instance where String is located.

Public Function LongArray(ParamArray values() As Variant) As Long()
    Dim temp() As Long
    ReDim temp(LBound(values) To UBound(values))

    Dim index As Long
    For index = LBound(temp) To UBound(temp)
        temp(index) = values(index)
    Next
    LongArray = temp
End Function

Other Data Type examples could include:

  • Single
  • Double
  • Date

The beauty is an error will be thrown when a value is not the correct data type and it can not be converted over, you will receive a Run-time error '13': Type mismatch error.

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

Содержание:

  • Объявление массивов
  • Назначение значений массиву
  • Многомерные массивы
  • Объявление ReDim
  • Методы массива
  • Функции для работы с массивами
  • LBound
  • UBound
  • Split
  • Join
  • Filter
  • IsArray
  • Erase

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

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

'Method 1 : Using Dim
Dim arr1()	'Without Size

'Method 2 : Mentioning the Size
Dim arr2(5)  'Declared with size of 5

'Method 3 : using 'Array' Parameter
Dim arr3
arr3 = Array("apple","Orange","Grapes")
  • Хотя размер массива указывается как 5, он может содержать 6 значений, поскольку индекс массива начинается с ZERO.
  • Индекс массива не может быть отрицательным.
  • Массивы VBScript могут хранить любой тип переменной в массиве. Следовательно, массив может хранить целое число, строку или символы в одной переменной массива.

Назначение значений массиву

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

Пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim arr(5)
   arr(0) = "1"           'Number as String
   arr(1) = "VBScript"    'String
   arr(2) = 100 		   'Number
   arr(3) = 2.45 		   'Decimal Number
   arr(4) = #10/07/2013#  'Date
   arr(5) = #12.45 PM#    'Time
  
   msgbox("Value stored in Array index 0 : " & arr(0))
   msgbox("Value stored in Array index 1 : " & arr(1))
   msgbox("Value stored in Array index 2 : " & arr(2))
   msgbox("Value stored in Array index 3 : " & arr(3))
   msgbox("Value stored in Array index 4 : " & arr(4))
   msgbox("Value stored in Array index 5 : " & arr(5))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Value stored in Array index 0 : 1
Value stored in Array index 1 : VBScript
Value stored in Array index 2 : 100
Value stored in Array index 3 : 2.45
Value stored in Array index 4 : 7/10/2013
Value stored in Array index 5 : 12:45:00 PM

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

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

пример

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

Private Sub Constant_demo_Click()
   Dim arr(2,3) as Variant	' Which has 3 rows and 4 columns
   arr(0,0) = "Apple" 
   arr(0,1) = "Orange"
   arr(0,2) = "Grapes"           
   arr(0,3) = "pineapple" 
   arr(1,0) = "cucumber"           
   arr(1,1) = "beans"           
   arr(1,2) = "carrot"           
   arr(1,3) = "tomato"           
   arr(2,0) = "potato"             
   arr(2,1) = "sandwitch"            
   arr(2,2) = "coffee"             
   arr(2,3) = "nuts"            
           
   msgbox("Value in Array index 0,1 : " &  arr(0,1))
   msgbox("Value in Array index 2,2 : " &  arr(2,2))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Value stored in Array index : 0 , 1 : Orange
Value stored in Array index : 2 , 2 : coffee

Объявление ReDim

Оператор ReDim используется для объявления переменных динамического массива и распределения или перераспределения пространства для хранения.

Синтаксис ReDim [Preserve] varname(subscripts) [, varname(subscripts)]
Параметр Описание

  • Preserve — необязательный параметр, используемый для сохранения данных в существующем массиве при изменении размера последнего измерения.
  • Varname — обязательный параметр, который обозначает имя переменной, которое должно соответствовать стандартным соглашениям об именах.
  • Subscript — требуемый параметр, который указывает размер массива.

пример

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

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

Private Sub Constant_demo_Click()
   Dim a() as variant
   i = 0
   redim a(5)
   a(0) = "XYZ"
   a(1) = 41.25
   a(2) = 22
  
   REDIM PRESERVE a(7)
   For i = 3 to 7
   a(i) = i
   Next
  
   'to Fetch the output
   For i = 0 to ubound(a)
      Msgbox a(i)
   Next
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

XYZ
41.25
22
3
4
5
6
7

Методы массива

В VBScript есть встроенные функции, которые помогают разработчикам эффективно обрабатывать массивы. Все методы, которые используются вместе с массивами, перечислены ниже. Чтобы узнать об этом, нажмите на имя метода.

Функции для работы с массивами

LBound

Функция LBound возвращает наименьший индекс указанного массива.Следовательно, LBound массива — ZERO.

Синтаксис LBound(ArrayName[,dimension])
Параметы и Описание

  • ArrayName — обязательный параметр. Этот параметр соответствует имени массива.
  • Размер — необязательный параметр. Это принимает целочисленное значение, соответствующее размеру массива. Если это «1», то он возвращает нижнюю границу первого измерения;если это «2», то он возвращает нижнюю границу второго измерения и так далее.

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim arr(5) as Variant
   arr(0) = "1"           'Number as String
   arr(1) = "VBScript     'String
   arr(2) = 100           'Number
   arr(3) = 2.45          'Decimal Number
   arr(4) = #10/07/2013#  'Date
   arr(5) = #12.45 PM#    'Time
   msgbox("The smallest Subscript value of  the given array is : " & LBound(arr))

   ' For MultiDimension Arrays :
   Dim arr2(3,2) as Variant
   msgbox("The smallest Subscript of the first dimension of arr2 is : " & LBound(arr2,1))
   msgbox("The smallest Subscript of the Second dimension of arr2 is : " & LBound(arr2,2))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

The smallest Subscript value of the given array is : 0
The smallest Subscript of the first dimension of arr2 is : 0
The smallest Subscript of the Second dimension of arr2 is : 0

Функция, которая возвращает целое число, соответствующее наименьшему индексу данных массивов.

UBound

Функция UBound возвращает наибольший индекс указанного массива.Следовательно, это значение соответствует размеру массива.

Синтаксис UBound(ArrayName[,dimension])
Параметры и Описание

  • ArrayName — обязательный параметр. Этот параметр соответствует имени массива.
  • Размер — необязательный параметр. Это принимает целочисленное значение, соответствующее размеру массива. Если это «1», то он возвращает нижнюю границу первого измерения;если он равен «2», то он возвращает нижнюю границу второго измерения и т. д.

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim arr(5) as Variant
   arr(0) = "1"           'Number as String
   arr(1) = "VBScript     'String
   arr(2) = 100           'Number
   arr(3) = 2.45          'Decimal Number
   arr(4) = #10/07/2013#  'Date
   arr(5) = #12.45 PM#    'Time
   msgbox("The smallest Subscript value of  the given array is : " & UBound(arr))

   ' For MultiDimension Arrays :
   Dim arr2(3,2) as Variant
   msgbox("The smallest Subscript of the first dimension of arr2 is : " & UBound(arr2,1))
   msgbox("The smallest Subscript of the Second dimension of arr2 is : " & UBound(arr2,2))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

The Largest Subscript value of the given array is : 5
The Largest Subscript of the first dimension of arr2 is : 3
The Largest Subscript of the Second dimension of arr2 is : 2

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

Split

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

Синтаксис Split(expression [,delimiter[, count[, compare]]])
Параметры и Описание

  • Выражение — требуемый параметр. Строковое выражение, которое может содержать строки с разделителями.
  • Разделитель — необязательный параметр. Параметр, который используется для преобразования в массивы на основе разделителя.
  • Count — необязательный параметр. Количество подстрок, которые нужно вернуть, и если указано как -1, то возвращаются все подстроки.
  • Compare — Необязательный параметр. Этот параметр указывает, какой метод сравнения следует использовать.
  • 0 = vbBinaryCompare — выполняет двоичное сравнение
  • 1 = vbTextCompare — выполняет текстовое сравнение

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   ' Splitting based on delimiter comma '$'
   Dim a as Variant
   Dim b as Variant
   
   a = Split("Red $ Blue $ Yellow","$")
   b = ubound(a)
   
   For i = 0 to b
      msgbox("The value of array in " & i & " is :"  & a(i))
   Next
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

The value of array in 0 is :Red
The value of array in 1 is : Blue
The value of array in 2 is : Yellow

Функция, которая возвращает массив, содержащий указанное количество значений. Разделить на разделитель.

Join

Это функция, которая возвращает строку, содержащую указанное количество подстрок в массиве. Это полная противоположная функция метода разделения.

Синтаксис Join(List[,delimiter])
Параметры и Описание

  • Список — требуемый параметр. Массив, содержащий подстроки, которые должны быть соединены.
  • Разделитель — необязательный параметр. Символ, который используется как разделитель при возврате строки. По умолчанию разделителем является Space.

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   ' Join using spaces
   a = array("Red","Blue","Yellow")
   b = join(a)
   msgbox("The value of b " & " is :"  & b)
  
   ' Join using $
   b = join(a,"$")
   msgbox("The Join result after using delimiter is : " & b)
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

The value of b is :Red Blue Yellow
The Join result after using delimiter is : Red$Blue$Yellow

Функция, которая возвращает строку, содержащую указанное количество подстрок в массиве. Это полная противоположная функция метода разделения.

Filter

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

Синтаксис Filter(inputstrings, value[, include [,compare]])
Параметры и Описание

  • Inputstrings — обязательный параметр. Этот параметр соответствует массиву строк для поиска.
  • Значение — требуемый параметр. Этот параметр соответствует строке для поиска по параметру inputstrings.
  • Include — необязательный параметр. Это логическое значение, которое указывает, следует ли возвращать подстроки, которые включают или исключают.
  • Compare — Необязательный параметр. Этот параметр описывает, какой метод сравнения строк должен использоваться.
  • 0 = vbBinaryCompare — выполняет двоичное сравнение
  • 1 = vbTextCompare — выполняет текстовое сравнение

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim a,b,c,d as Variant
   a = array("Red","Blue","Yellow")
   b = Filter(a,"B")
   c = Filter(a,"e")
   d = Filter(a,"Y")
  
   For each x in b
      msgbox("The Filter result 1: " & x)
   Next
  
   For each y in c
      msgbox("The Filter result 2: " & y)
   Next
  
   For each z in d
      msgbox("The Filter result 3: " & z)
   Next
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.p The Filter result 1: Blue
The Filter result 2: Red
The Filter result 2: Blue
The Filter result 2: Yellow
The Filter result 3: Yellow

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

IsArray

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

Синтаксис IsArray(variablename)
пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim a,b as Variant
   a = array("Red","Blue","Yellow")
   b = "12345"
  
   msgbox("The IsArray result 1 : " & IsArray(a))
   msgbox("The IsArray result 2 : " & IsArray(b))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

The IsArray result 1 : True
The IsArray result 2 : False

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

Erase

Функция Erase используется для сброса значений массивов фиксированного размера и освобождения памяти динамических массивов.Он ведет себя в зависимости от типа массивов.

Синтаксис Erase ArrayName

  • Фиксированный числовой массив, каждый элемент в массиве сбрасывается до нуля.
  • Исправлен строковый массив, каждый элемент в массиве сбрасывается до нулевой длины «».
  • Массив объектов, каждый элемент в массиве сбрасывается до специального значения Nothing.

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
   Dim NumArray(3)
   NumArray(0) = "VBScript"
   NumArray(1) = 1.05
   NumArray(2) = 25
   NumArray(3) = #23/04/2013#
  
   Dim DynamicArray()
   ReDim DynamicArray(9)   ' Allocate storage space.
  
   Erase NumArray          ' Each element is reinitialized.
   Erase DynamicArray      ' Free memory used by array.
  
   ' All values would be erased.
   msgbox("The value at Zeroth index of NumArray is " & NumArray(0))
   msgbox("The value at First index of NumArray is " & NumArray(1))
   msgbox("The value at Second index of NumArray is " & NumArray(2))
   msgbox("The value at Third index of NumArray is " & NumArray(3))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

The value at Zeroth index of NumArray is
The value at First index of NumArray is
The value at Second index of NumArray is
The value at Third index of NumArray is

Функция, которая восстанавливает выделенную память для переменных массива.

 С уважением, авторы сайта Компьютерапия

Понравилась статья? Поделитесь ею с друзьями и напишите отзыв в комментариях!

I want to declare a dynamic string array, then make calls to each of the other procedures. This is what I have, I thought it would work but I keep getting errors.

Option Explicit

Sub Main()

   Public ListArr() As String

   Application.Run "Get_Input_List"

End Sub

Function Get_Input_List(ByRef ListArr() As String) As String

   Dim list As String
   Dim MesBox As String

  list = InputBox("Please enters word to sort using a comma with no space to separate", "Words")

  ListArr = Split(list, ",")

  MsgBox ListArr(1)

End Function

Deduplicator's user avatar

Deduplicator

44.3k7 gold badges65 silver badges115 bronze badges

asked Sep 21, 2016 at 0:42

LRoyster's user avatar

A couple issues here. First, Public can only be used as an access modifier for Module level variables — not local ones, so it should be Dim ListArr() As String. Second, you don’t need to use Application.Run to call procedures in the same project. If you did, you aren’t passing the required parameter (which can’t be passed ByRef via Application.Run anyway). Third, Get_Input_List is a function, so you should probably return the result of the Split. Right now it always returns vbNullString. I’m guessing that you’re looking for something more like this:

Option Explicit

Sub Main()
   Dim ListArr() As String
   ListArr = Get_Input_List

   Dim inputWord As Variant
   For Each inputWord In ListArr
        MsgBox inputWord
   Next
End Sub

Function Get_Input_List() As String()
    Dim list As String

    list = InputBox("Please enter words to sort separated with a comma and no spaces", "Words")
    Get_Input_List = Split(list, ",")
End Function

answered Sep 21, 2016 at 0:52

Comintern's user avatar

CominternComintern

21.7k5 gold badges33 silver badges80 bronze badges

In VBA, a String Array is nothing but an array variable that can hold more than one string value with a single variable.

For example, look at the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more below.

Table of contents
  • Excel VBA String Array
    • Examples of String Array in Excel VBA
      • Example #1
      • Example #2
      • Example #3
    • Things to Remember
    • Recommended Articles

Code:

Sub String_Array_Example()

Dim CityList(1 To 5) As Variant

CityList(1) = "Bangalore"
CityList(2) = "Mumbai"
CityList(3) = "Kolkata"
CityList(4) = "Hyderabad"
CityList(5) = "Orissa"

MsgBox CityList(1) & ", " & CityList(2) & ", " & CityList(3) & ", " & CityList(4) & ", " & CityList(5)

End Sub

In the above code, we have declared an array variable and assigned the length of an array as 1 to 5.

Dim CityList(1 To 5) As Variant

Next, we have written a code to show these city names in the message box.

CityList(1) = "Bangalore"

CityList(2) = "Mumbai"

CityList(3) = "Kolkata"

CityList(4) = "Hyderabad"

CityList(5) = "Orissa"

Next, we have written a code to show these city names in the message box.

MsgBox CityList(1) & ", " & CityList(2) & ", " & CityList(3) & ", " & CityList(4) & ", " & CityList(5)

When we run this code, we will get a message box that shows all the city names in a single message box.

VBA String Array Example 1-1

We all know this has saved much time from our schedule by eliminating the task of declaring individual variables for each city. However, one more thing you need to learn is we can still reduce the code of lines we write for string values. So, let’s look at how we write code for VBA stringString functions in VBA do not replace the string; instead, this function creates a new string. There are numerous string functions in VBA, all of which are classified as string or text functions.read more arrays.

Examples of String Array in Excel VBA

Below are examples of an Excel VBA string array.

You can download this VBA String Array Excel Template here – VBA String Array Excel Template

Example #1

As we have seen in the above code, we learned we could store more than one value in the variable based on the array size.

We do not need to decide the array length well in advance.

Code:

Sub String_Array_Example1()

Dim CityList() As Variant

End Sub

VBA String Array Example 1-1

As you can see above, we have not written any lengths in the parenthesis. So now, for this variable, let’s insert values using VBA ARRAY functionArrays are used in VBA to define groups of objects. There are nine different array functions in VBA: ARRAY, ERASE, FILTER, ISARRAY, JOIN, LBOUND, REDIM, SPLIT, and UBOUND.read more.

VBA String Array Example 1-2.png

Inside the array, pass the values on double quotes, each separated by a comma (,).

Code:

Sub String_Array_Example()

Dim CityList() As Variant

CityList = Array("Bangalore", "Mumbai", "Kolkata", "Hyderabad", "Orissa")

End Sub

VBA String Array Example 1-3.png

Now, retain the old code to show the result of city names in the message box in VBAVBA MsgBox function is an output function which displays the generalized message provided by the developer. This statement has no arguments and the personalized messages in this function are written under the double quotes while for the values the variable reference is provided.read more.

Code:

Sub String_Array_Example1()

Dim CityList() As Variant

CityList = Array("Bangalore", "Mumbai", "Kolkata", "Hyderabad", "Orissa")

MsgBox CityList(0) & ", " & CityList(1) & ", " & CityList(2) & ", " & CityList(3) & ", " & CityList(4)

End Sub

One change we have made in the above code is that we have not decided on the lower limit and upper limit of an array variable. Therefore, the ARRAY function array count will start from 0, not 1.

So, that is the reason we have mentioned the values as  CityList(0), ClityList(1), CityList(2), CityList(3), and CityList(4).

Now, run the code through excel shortcut keyAn Excel shortcut is a technique of performing a manual task in a quicker way.read more F5 or manually. Again, we get the same result as the previous code.

VBA String Array Example 1.gif

Example #2

VBA String Array with LBOUND & UBOUND Functions

If you don’t want to show all the city lists in a single message box, then you need to include loops and define one more variable for loops.

VBA String Array Example 1-6

Now, to include FOR NEXT loop, we are unsure how many times we need to run the code. Of course, we can decide five times in this case, but that is not the right way to approach the problem. So, how about the idea of auto lower and higher level array length identifiers?

When we open FOR NEXT loop, we usually decide the loop length as 1 to 5 or 1 to 10, depending upon the situation. So, instead of manually entering the numbers, let’s automatically use the LBOUND and UBOUND functions to decide on the lower and upper values.

VBA String Array Example 1-7

For LBound and Ubound, we have supplied an array name, CityList. The VBA LBoundLBound in VBA or “Lower Bound” extracts the lowest number of an array. For example, if the array says “Dim ArrayCount (2 to 10) as String” then using LBound function we can find the least number of the array length i.e. 2.read more identifies the array variable’s lower value. The VBA UBound functionUBOUND, also known as Upper Bound, is a VBA function that is used in conjunction with its opposite function, LBOUND, also known as Lower Bound. This function is used to determine the length of an array in a code, and as the name suggests, UBOUND is used to define the array’s upper limit.read more identifies the upper value of the array variable.

Now, show the value in the message box. Instead of inserting the serial number, let the loop variable “k” take the array value automatically.

Code:

Sub String_Array_Example1()

Dim CityList() As Variant

Dim k As Integer

CityList = Array("Bangalore", "Mumbai", "Kolkata", "Hyderabad", "Orissa")

For k = LBound(CityList) To UBound(CityList)

MsgBox CityList(k)

Next k

End Sub

LBound & UBound Example 1-8

Now, the message box will show each city name separately.

VBA String Array Example 1.gif

Example #3

VBA String Array with Split Function

Now, assume you have city names like the one below.

Bangalore;Mumbai;Kolkata;Hydrabad;Orissa

In this case, all the cities combine with the colon separating each city. Therefore, we need to use the SPLIT function to separate each city in such cases.

Split Example 2

For Expression, supply the city list.

Code:

Sub String_Array_Example2()

Dim CityList() As String

Dim k As Integer

CityList = Split("Bangalore;Mumbai;Kolkata;Hydrabad;Orissa",

For k = LBound(CityList) To UBound(CityList)
MsgBox CityList(k)
Next k

End Sub

Split Example 2-1

The next argument is “Delimiter,” which is the one character separating each city from other cities. In this case, “Colon.”

Code:

Sub String_Array_Example2()

Dim CityList() As String

Dim k As Integer

CityList = Split("Bangalore;Mumbai;Kolkata;Hydrabad;Orissa", ";")

For k = LBound(CityList) To UBound(CityList)
MsgBox CityList(k)
Next k

End Sub

split Example 2-2.png

Now, the SPLIT function split values determine the highest array length.

Things to Remember

  • The LBOUND and UBOUND are functions to determine the array lengths.
  • The ARRAY function can hold many values for a declared variable.
  • Once we want to use the ARRAY function, do not decide the array length.

Recommended Articles

This article is a guide to VBA String Array. Here, we discuss how to declare the VBA string array variable, which can hold more than one string value, along with practical examples and a downloadable template. Below you can find some useful Excel VBA articles: –

  • VBA String Comparison
  • Find Array Size in VBA
  • SubString in Excel VBA
  • Variant Data Type in VBA

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

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

Пример 1. Создание (объявление) одномерного массива выполняется, так:

Dim Arr1(10) As Integer
Dim Arr2(5 To 10) As String
Dim Arr3() As Long

В данном примере объявляются: одномерный массив Arr1, содержащий ячейки с 0-й до 10-й типа Integer, массив Arr2, содержащий ячейки с 5-й до 10-й типа String и динамический массив Arr3.

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

Пример 2. Инициализация динамического массива и изменение его размеров

Dim Arr3() As Long
ReDim Preserve Arr3(10)
ReDim Preserve Arr3(20)

В данном примере мы сначала с помощью ReDim задали размер динамического массива в 11 элементов (c 0-го по 10-й), а затем снова увеличили размер до 21-го элемента. Кроме того, использовали ключевое слово Preserve — означающее, что нужно сохранить уже имеющиеся элементы с их значениями (без этого ключевого слова массив обнуляется).

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

Пример 3. Объявление многомерного массива

Dim Arr4(10, 10) As Integer
Dim Arr5(5 To 10, 15 To 20, 30) As String

Arr4 — двумерных массив 11х11 элементов, а массив Arr5 — трехмерный.

Пример 4. Создание массива массивов

В следующем примере массив Arr2 будет содержать элементы другого массива Arr1

Dim Arr1 As Variant
Dim Arr2(10) As Variant
Arr1 = Array(10, 20, 30)
Arr2(0) = Arr1
For i = LBound(Arr2(0)) To UBound(Arr2(0))
  MsgBox Arr2(0)(i) ' Выведет последовательно 10, 20 и 30
Next i

Определение нижней и верхней границы массива

Чтобы узнать какой самый наименьший индекс у массива и какой самый максимальный индекс массива, нужно использовать функции LBound для определения нижней границы и UBound для определения верхней границы.

Пример 5. Определение границ массива

Dim Arr1(2 To 15) As Integer
MsgBox LBound(Arr1) ' Выведет: 2
MsgBox UBound(Arr1) ' Выведет: 15
Dim Arr2() As Integer
ReDim Arr2(8)
MsgBox LBound(Arr2) ' Выведет: 0
MsgBox UBound(Arr2) ' Выведет: 8

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

Dim Arr(1 To 10, 5 To 20) As Integer
MsgBox LBound(Arr, 2) ' Выведет: 5
MsgBox UBound(Arr, 2) ' Выведет: 20

Задание нижней границы по-умолчанию

Иногда бывает очень не удобно, что VBA начинает нумерацию элементов массивов с нуля (0), это часто может привести к путанице и усложнению кода программы. Для решения этой проблемы есть специальный оператор Option Base, аргумент которого может быть 0 или 1. Указав значение 1, индексация массивов будет начинаться с 1, а не с 0.

Пример 6. Указание нижней границы по-умолчанию.

Option Base 1

Sub Test()
Dim Arr1(10) As Integer
MsgBox LBound(Arr1)
End Sub

В данном примере я намеренно использовал процедуру, чтобы показать, что Option Base нужно применять не внутри процедур и функций, а в разделе «Declarations». В результате выполнения процедуры Test будет отображено сообщение с индексом нижней границы массива, т.е. «1».

Примечание: Оператор Option Base так же влияет на функцию Array и не влияет на функцию Split (будут рассмотрены ниже), что означает, что при задании «Option Base 1», функция Array вернет массив с индексацией с 1-цы, а функция Split вернет массив с индексацией с 0.

Запись данных в массивы

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

Пример 7. Запись данных в массив в цикле.

Dim Arr(10) As Integer
For i = 0 To 10
    Arr(i) = i * 2
Next i

Пример 8. Запись заранее известных данных с помощью Array

Dim Arr()
Arr = Array("красный", "зеленый", "синий")
MsgBox Arr(2)

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

Пример 9. Получение массива из строки с разделителями

Dim Arr() As String
Arr = Split("красный;зеленый;синий", ";")
MsgBox Arr(2)

Обход элементов массива

Обычно, массивы используются для хранения большого кол-ва данных, а не 1-2 значений, поэтому чтобы получить все эелементы и использовать их для чего-то, обычно используют циклы. Наиболее удобны в этом плане циклы For и For Each.

Пример 10. Обход элементов массива циклом For.

Dim Sum As Integer
Dim Arr()
Arr = Array(10, 20, 30)
For i = 0 To 2
    Sum = Sum + Arr(i)
Next i
MsgBox Sum

Пример 11. Обход элементов массива циклом For Each.

Dim Sum As Integer
Dim Val As Variant
Dim Arr()
Arr = Array(10, 20, 30)
For Each Val In Arr
    Sum = Sum + Val
Next
MsgBox Sum

Иногда, бывает необходимость работы с массивом внутри других типов циклов, но получение значение элемента, всё-равно в них будет таким же, как и в цикле For, т.е. через индекс элемента.

Return to VBA Code Examples

In this Article

  • Declaring a String variable
  • Declaring a Static String Array
  • Declaring a Variant Array using the Array function
  • Declaring a String Array using the Split Function

This tutorial will teach you how to declare and initialize a string array in VBA.

Declaring a String variable

When you declare a string variable in VBA, you populate it by adding a single string to the variable which you can then use in your VBA code.

Dim strName as String
StrName = "Bob Smith"

Declaring a Static String Array

If you want to populate an array with a string of values, you can create a STATIC string array to do so.

Dim StrName(2) as String 
StrName(0) = "Bob Smith"
StrName(1) = "Tom Jones"
StrName(2) = "Mel Jenkins"

Remember that the Index of an Array begins at zero – so we declare the Array size to be 2 – which then enables the Array to hold 3 values.

Instead, you can explicitly define the start and end positions of an array:

Dim StrName(1 to 3) as String 
StrName(1) = "Bob Smith"
StrName(2) = "Tom Jones"
StrName(3) = "Mel Jenkins"

Declaring a Variant Array using the Array function

If you want to populate an array with a string of values without implicitly stating the size of the Array, you can create a variant array and populate it using the Array function.

Dim strName as Variant
strName = Array("Bob Smith", "Tom Jones", "Mel Jenkins")

Declaring a String Array using the Split Function

If you want to keep the variable as a string but do not want to implicitly state the size of the Array, you would need to use the Split function to populate the array.

Dim strName() as String 
strNames = Split("Bob Smith, Tom Jones, Mel Jenkins")

The Split function allows you to keep the data type (eg String) while splitting the data into the individual values.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

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

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)

Понравилась статья? Поделить с друзьями:
  • Word vba add row and table
  • Word vba activedocument saved
  • Word vba activedocument save
  • Word vba activedocument range
  • Word vast in a sentence