Array vba excel примеры

This post provides an in-depth look at the VBA array which is a very important part of the Excel VBA programming language. It covers everything you need to know about the VBA array.

We will start by seeing what exactly is the VBA Array is and why you need it.

Below you will see a quick reference guide to using the VBA Array.  Refer to it anytime you need a quick reminder of the VBA Array syntax.

The rest of the post provides the most complete guide you will find on the VBA array.

Related Links for the VBA Array

Loops are used for reading through the VBA Array:
For Loop
For Each Loop

Other data structures in VBA:
VBA Collection – Good when you want to keep inserting items as it automatically resizes.
VBA ArrayList – This has more functionality than the Collection.
VBA Dictionary – Allows storing a KeyValue pair. Very useful in many applications.

The Microsoft guide for VBA Arrays can be found here.

A Quick Guide to the VBA Array

Task Static Array Dynamic Array
Declare Dim arr(0 To 5) As Long Dim arr() As Long
Dim arr As Variant
Set Size See Declare above ReDim arr(0 To 5)As Variant
Get Size(number of items) See ArraySize function below. See ArraySize function below.
Increase size (keep existing data) Dynamic Only ReDim Preserve arr(0 To 6)
Set values arr(1) = 22 arr(1) = 22
Receive values total = arr(1) total = arr(1)
First position LBound(arr) LBound(arr)
Last position Ubound(arr) Ubound(arr)
Read all items(1D) For i = LBound(arr) To UBound(arr)
Next i

Or
For i = LBound(arr,1) To UBound(arr,1)
Next i
For i = LBound(arr) To UBound(arr)
Next i

Or
For i = LBound(arr,1) To UBound(arr,1)
Next i
Read all items(2D) For i = LBound(arr,1) To UBound(arr,1)
  For j = LBound(arr,2) To UBound(arr,2)
  Next j
Next i
For i = LBound(arr,1) To UBound(arr,1)
  For j = LBound(arr,2) To UBound(arr,2)
  Next j
Next i
Read all items Dim item As Variant
For Each item In arr
Next item
Dim item As Variant
For Each item In arr
Next item
Pass to Sub Sub MySub(ByRef arr() As String) Sub MySub(ByRef arr() As String)
Return from Function Function GetArray() As Long()
    Dim arr(0 To 5) As Long
    GetArray = arr
End Function
Function GetArray() As Long()
    Dim arr() As Long
    GetArray = arr
End Function
Receive from Function Dynamic only Dim arr() As Long
Arr = GetArray()
Erase array Erase arr
*Resets all values to default
Erase arr
*Deletes array
String to array Dynamic only Dim arr As Variant
arr = Split(«James:Earl:Jones»,»:»)
Array to string Dim sName As String
sName = Join(arr, «:»)
Dim sName As String
sName = Join(arr, «:»)
Fill with values Dynamic only Dim arr As Variant
arr = Array(«John», «Hazel», «Fred»)
Range to Array Dynamic only Dim arr As Variant
arr = Range(«A1:D2»)
Array to Range Same as dynamic Dim arr As Variant
Range(«A5:D6») = arr

Download the Source Code and Data

Please click on the button below to get the fully documented source code for this article.

What is the VBA Array and Why do You Need It?

A VBA array is a type of variable. It is used to store lists of data of the same type. An example would be storing a list of countries or a list of weekly totals.

In VBA a normal variable can store only one value at a time.

In the following example we use a variable to store the marks of a student:

' Can only store 1 value at a time
Dim Student1 As Long
Student1 = 55

If we wish to store the marks of another student then we need to create a second variable.

In the following example, we have the marks of five students:

VBa Arrays

Student Marks

We are going to read these marks and write them to the Immediate Window.

Note: The function Debug.Print writes values to the Immediate  Window. To view this window select View->Immediate Window from the menu( Shortcut is Ctrl + G)

ImmediateWindow

ImmediateSampeText

As you can see in the following example we are writing the same code five times – once for each student:

' https://excelmacromastery.com/
Public Sub StudentMarks()

    ' Get the worksheet called "Marks"
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets("Marks")
    
    ' Declare variable for each student
    Dim Student1 As Long
    Dim Student2 As Long
    Dim Student3 As Long
    Dim Student4 As Long
    Dim Student5 As Long

    ' Read student marks from cell
    Student1 = sh.Range("C" & 3).Value
    Student2 = sh.Range("C" & 4).Value
    Student3 = sh.Range("C" & 5).Value
    Student4 = sh.Range("C" & 6).Value
    Student5 = sh.Range("C" & 7).Value

    ' Print student marks
    Debug.Print "Students Marks"
    Debug.Print Student1
    Debug.Print Student2
    Debug.Print Student3
    Debug.Print Student4
    Debug.Print Student5

End Sub

The following is the output from the example:

VBA Arrays

Output

The problem with using one variable per student is that you need to add code for each student. Therefore if you had a thousand students in the above example you would need three thousand lines of code!

Luckily we have arrays to make our life easier. Arrays allow us to store a list of data items in one structure.

The following code shows the above student example using an array:

' ExcelMacroMastery.com
' https://excelmacromastery.com/excel-vba-array/
' Author: Paul Kelly
' Description: Reads marks to an Array and write
' the array to the Immediate Window(Ctrl + G)
' TO RUN: Click in the sub and press F5
Public Sub StudentMarksArr()

    ' Get the worksheet called "Marks"
    Dim sh As Worksheet
    Set sh = ThisWorkbook.Worksheets("Marks")

    ' Declare an array to hold marks for 5 students
    Dim Students(1 To 5) As Long

    ' Read student marks from cells C3:C7 into array
    ' Offset counts rows from cell C2.
    ' e.g. i=1 is C2 plus 1 row which is C3
    '      i=2 is C2 plus 2 rows which is C4
    Dim i As Long
    For i = 1 To 5
        Students(i) = sh.Range("C2").Offset(i).Value
    Next i

    ' Print student marks from the array to the Immediate Window
    Debug.Print "Students Marks"
    For i = LBound(Students) To UBound(Students)
        Debug.Print Students(i)
    Next i

End Sub

The advantage of this code is that it will work for any number of students. If we have to change this code to deal with 1000 students we only need to change the (1 To 5) to (1 To 1000) in the declaration. In the prior example we would need to add approximately five thousand lines of code.

Let’s have a quick comparison of variables and arrays. First we compare the declaration:

        ' Variable
        Dim Student As Long
        Dim Country As String

        ' Array
        Dim Students(1 To 3) As Long
        Dim Countries(1 To 3) As String

Next we compare assigning a value:

        ' assign value to variable
        Student1 = .Cells(1, 1) 

        ' assign value to first item in array
        Students(1) = .Cells(1, 1)

Finally we look at writing the values:

        ' Print variable value
        Debug.Print Student1

        ' Print value of first student in array
        Debug.Print Students(1)

As you can see, using variables and arrays is quite similar.

The fact that arrays use an index(also called a subscript) to access each item is important. It means we can easily access all the items in an array using a For Loop.

Now that you have some background on why arrays are useful let’s go through them step by step.

Two Types of VBA Arrays

There are two types of VBA arrays:

  1. Static – an array of fixed length.
  2. Dynamic(not to be confused with the Excel Dynamic Array) – an array where the length is set at run time.

The difference between these types is mostly in how they are created. Accessing values in both array types is exactly the same. In the following sections we will cover both of these types.

VBA Array Initialization

A static array is initialized as follows:

' https://excelmacromastery.com/
Public Sub DecArrayStatic()

    ' Create array with locations 0,1,2,3
    Dim arrMarks1(0 To 3) As Long

    ' Defaults as 0 to 3 i.e. locations 0,1,2,3
    Dim arrMarks2(3) As Long

    ' Create array with locations 1,2,3,4,5
    Dim arrMarks3(1 To 5) As Long

    ' Create array with locations 2,3,4 ' This is rarely used
    Dim arrMarks4(2 To 4) As Long

End Sub

VBA Arrays

An Array of 0 to 3

As you can see the length is specified when you declare a static array. The problem with this is that you can never be sure in advance the length you need. Each time you run the Macro you may have different length requirements.

If you do not use all the array locations then the resources are being wasted. So if you need more locations you can use ReDim but this is essentially creating a new static array.

The dynamic array does not have such problems. You do not specify the length when you declare it. Therefore you can then grow and shrink as required:

' https://excelmacromastery.com/
Public Sub DecArrayDynamic()

    ' Declare  dynamic array
    Dim arrMarks() As Long

    ' Set the length of the array when you are ready
    ReDim arrMarks(0 To 5)

End Sub

The dynamic array is not allocated until you use the ReDim statement. The advantage is you can wait until you know the number of items before setting the array length. With a static array you have to state the length upfront.

To give an example. Imagine you were reading worksheets of student marks. With a dynamic array you can count the students on the worksheet and set an array to that length. With a static array you must set the length to the largest possible number of students.

Assigning Values to VBA Array

To assign values to an array you use the number of the location. You assign the value for both array types the same way:

' https://excelmacromastery.com/
Public Sub AssignValue()

    ' Declare  array with locations 0,1,2,3
    Dim arrMarks(0 To 3) As Long

    ' Set the value of position 0
    arrMarks(0) = 5

    ' Set the value of position 3
    arrMarks(3) = 46

    ' This is an error as there is no location 4
    arrMarks(4) = 99

End Sub

VBA Array 2

The array with values assigned

The number of the location is called the subscript or index. The last line in the example will give a “Subscript out of Range” error as there is no location 4 in the array example.

VBA Array Length

There is no native function for getting the number of items in an array. I created the ArrayLength function below to return the number of items in any array no matter how many dimensions:

' https://excelmacromastery.com/
Function ArrayLength(arr As Variant) As Long

    On Error Goto eh
    
    ' Loop is used for multidimensional arrays. The Loop will terminate when a
    ' "Subscript out of Range" error occurs i.e. there are no more dimensions.
    Dim i As Long, length As Long
    length = 1
    
    ' Loop until no more dimensions
    Do While True
        i = i + 1
        ' If the array has no items then this line will throw an error
        Length = Length * (UBound(arr, i) - LBound(arr, i) + 1)
        ' Set ArrayLength here to avoid returing 1 for an empty array
        ArrayLength = Length
    Loop

Done:
    Exit Function
eh:
    If Err.Number = 13 Then ' Type Mismatch Error
        Err.Raise vbObjectError, "ArrayLength" _
            , "The argument passed to the ArrayLength function is not an array."
    End If
End Function

You can use it like this:

' Name: TEST_ArrayLength
' Author: Paul Kelly, ExcelMacroMastery.com
' Description: Tests the ArrayLength functions and writes
'              the results to the Immediate Window(Ctrl + G)
Sub TEST_ArrayLength()
    
    ' 0 items
    Dim arr1() As Long
    Debug.Print ArrayLength(arr1)
    
    ' 10 items
    Dim arr2(0 To 9) As Long
    Debug.Print ArrayLength(arr2)
    
    ' 18 items
    Dim arr3(0 To 5, 1 To 3) As Long
    Debug.Print ArrayLength(arr3)
    
    ' Option base 0: 144 items
    ' Option base 1: 50 items
    Dim arr4(1, 5, 5, 0 To 1) As Long
    Debug.Print ArrayLength(arr4)
    
End Sub

Using the Array and Split function

You can use the Array function to populate an array with a list of items. You must declare the array as a type Variant. The following code shows you how to use this function.

    Dim arr1 As Variant
    arr1 = Array("Orange", "Peach","Pear")

    Dim arr2 As Variant
    arr2 = Array(5, 6, 7, 8, 12)

Arrays VBA

Contents of arr1 after using the Array function

The array created by the Array Function will start at index zero unless you use Option Base 1 at the top of your module. Then it will start at index one. In programming, it is generally considered poor practice to have your actual data in the code. However, sometimes it is useful when you need to test some code quickly.

The Split function is used to split a string into an array based on a delimiter. A delimiter is a character such as a comma or space that separates the items.

The following code will split the string into an array of four elements:

    Dim s As String
    s = "Red,Yellow,Green,Blue"

    Dim arr() As String
    arr = Split(s, ",")

Arrays VBA

The array after using Split

The Split function is normally used when you read from a comma-separated file or another source that provides a list of items separated by the same character.

Using Loops With the VBA Array

Using a For Loop allows quick access to all items in an array. This is where the power of using arrays becomes apparent. We can read arrays with ten values or ten thousand values using the same few lines of code. There are two functions in VBA called LBound and UBound. These functions return the smallest and largest subscript in an array. In an array arrMarks(0 to 3) the LBound will return 0 and UBound will return 3.

The following example assigns random numbers to an array using a loop. It then prints out these numbers using a second loop.

' https://excelmacromastery.com/
Public Sub ArrayLoops()

    ' Declare  array
    Dim arrMarks(0 To 5) As Long

    ' Fill the array with random numbers
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' Print out the values in the array
    Debug.Print "Location", "Value"
    For i = LBound(arrMarks) To UBound(arrMarks)
        Debug.Print i, arrMarks(i)
    Next i

End Sub

The functions LBound and UBound are very useful. Using them means our loops will work correctly with any array length. The real benefit is that if the length of the array changes we do not have to change the code for printing the values. A loop will work for an array of any length as long as you use these functions.

Using the For Each Loop with the VBA Array

You can use the For Each loop with arrays. The important thing to keep in mind is that it is Read-Only. This means that you cannot change the value in the array.

In the following code the value of mark changes but it does not change the value in the array.

    For Each mark In arrMarks
        ' Will not change the array value
        mark = 5 * Rnd
    Next mark

The For Each is loop is fine to use for reading an array. It is neater to write especially for a Two-Dimensional array as we will see.

    Dim mark As Variant
    For Each mark In arrMarks
        Debug.Print mark
    Next mark

Using Erase with the VBA Array

The Erase function can be used on arrays but performs differently depending on the array type.

For a static Array the Erase function resets all the values to the default. If the array is made up of long integers(i.e type Long) then all the values are set to zero. If the array is of strings then all the strings are set to “” and so on.

For a Dynamic Array the Erase function DeAllocates memory. That is, it deletes the array. If you want to use it again you must use ReDim to Allocate memory.

Let’s have a look an example for the static array. This example is the same as the ArrayLoops example in the last section with one difference – we use Erase after setting the values. When the value are printed out they will all be zero:

' https://excelmacromastery.com/
Public Sub EraseStatic()

    ' Declare  array
    Dim arrMarks(0 To 3) As Long

    ' Fill the array with random numbers
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' ALL VALUES SET TO ZERO
    Erase arrMarks

    ' Print out the values - there are all now zero
    Debug.Print "Location", "Value"
    For i = LBound(arrMarks) To UBound(arrMarks)
        Debug.Print i, arrMarks(i)
    Next i

End Sub

We will now try the same example with a dynamic. After we use Erase all the locations in the array have been deleted. We need to use ReDim if we wish to use the array again.

If we try to access members of this array we will get a “Subscript out of Range” error:

' https://excelmacromastery.com/
Public Sub EraseDynamic()

    ' Declare  array
    Dim arrMarks() As Long
    ReDim arrMarks(0 To 3)

    ' Fill the array with random numbers
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' arrMarks is now deallocated. No locations exist.
    Erase arrMarks

End Sub

Increasing the length of the VBA Array

If we use ReDim on an existing array, then the array and its contents will be deleted.

In the following example, the second ReDim statement will create a completely new array. The original array and its contents will be deleted.

' https://excelmacromastery.com/
Sub UsingRedim()

    Dim arr() As String
    
    ' Set array to be slots 0 to 2
    ReDim arr(0 To 2)
    arr(0) = "Apple"
    
    ' Array with apple is now deleted
    ReDim arr(0 To 3)

End Sub

If we want to extend the length of an array without losing the contents, we can use the Preserve keyword.

When we use Redim Preserve the new array must start at the same starting dimension e.g.

We cannot Preserve from (0 to 2) to (1 to 3) or to (2 to 10) as they are different starting dimensions.

In the following code we create an array using ReDim and then fill the array with types of fruit.

We then use Preserve to extend the length of the array so we don’t lose the original contents:

' https://excelmacromastery.com/
Sub UsingRedimPreserve()

    Dim arr() As String
    
    ' Set array to be slots 0 to 1
    ReDim arr(0 To 2)
    arr(0) = "Apple"
    arr(1) = "Orange"
    arr(2) = "Pear"
    
    ' Reset the length and keep original contents
    ReDim Preserve arr(0 To 5)

End Sub

You can see from the screenshots below, that the original contents of the array have been “Preserved”.

VBA Preserve

Before ReDim Preserve

VBA Preserve

After ReDim Preserve

Word of Caution: In most cases, you shouldn’t need to resize an array like we have done in this section. If you are resizing an array multiple times then you may want to consider using a Collection.

Using Preserve with Two-Dimensional Arrays

Preserve only works with the upper bound of an array.

For example, if you have a two-dimensional array you can only preserve the second dimension as this example shows:

' https://excelmacromastery.com/
Sub Preserve2D()

    Dim arr() As Long
    
    ' Set the starting length
    ReDim arr(1 To 2, 1 To 5)
    
    ' Change the length of the upper dimension
    ReDim Preserve arr(1 To 2, 1 To 10)

End Sub

If we try to use Preserve on a lower bound we will get the “Subscript out of range” error.

In the following code we use Preserve on the first dimension. Running this code will give the “Subscript out of range” error:

' https://excelmacromastery.com/
Sub Preserve2DError()

    Dim arr() As Long
    
    ' Set the starting length
    ReDim arr(1 To 2, 1 To 5)
    
    ' "Subscript out of Range" error
    ReDim Preserve arr(1 To 5, 1 To 5)

End Sub

When we read from a range to an array, it automatically creates a two-dimensional array, even if we have only one column.

The same Preserve rules apply. We can only use Preserve on the upper bound as this example shows:

' https://excelmacromastery.com/
Sub Preserve2DRange()

    Dim arr As Variant
    
    ' Assign a range to an array
    arr = Sheet1.Range("A1:A5").Value
    
    ' Preserve will work on the upper bound only
    ReDim Preserve arr(1 To 5, 1 To 7)

End Sub

Sorting the VBA Array

There is no function in VBA for sorting an array. We can sort the worksheet cells but this could be slow if there is a lot of data.

The QuickSort function below can be used to sort an array.

' https://excelmacromastery.com/
Sub QuickSort(arr As Variant, first As Long, last As Long)
  
  Dim vCentreVal As Variant, vTemp As Variant
  
  Dim lTempLow As Long
  Dim lTempHi As Long
  lTempLow = first
  lTempHi = last
  
  vCentreVal = arr((first + last)  2)
  Do While lTempLow <= lTempHi
  
    Do While arr(lTempLow) < vCentreVal And lTempLow < last
      lTempLow = lTempLow + 1
    Loop
    
    Do While vCentreVal < arr(lTempHi) And lTempHi > first
      lTempHi = lTempHi - 1
    Loop
    
    If lTempLow <= lTempHi Then
    
        ' Swap values
        vTemp = arr(lTempLow)

        arr(lTempLow) = arr(lTempHi)
        arr(lTempHi) = vTemp
      
        ' Move to next positions
        lTempLow = lTempLow + 1
        lTempHi = lTempHi - 1
      
    End If
    
  Loop
  
  If first < lTempHi Then QuickSort arr, first, lTempHi
  If lTempLow < last Then QuickSort arr, lTempLow, last
  
End Sub

You can use this function like this:

' https://excelmacromastery.com/
Sub TestSort()

    ' Create temp array
    Dim arr() As Variant
    arr = Array("Banana", "Melon", "Peach", "Plum", "Apple")
  
    ' Sort array
    QuickSort arr, LBound(arr), UBound(arr)

    ' Print arr to Immediate Window(Ctrl + G)
    Dim i As Long
    For i = LBound(arr) To UBound(arr)
        Debug.Print arr(i)
    Next i

End Sub

Passing the VBA Array to a Sub

Sometimes you will need to pass an array to a procedure. You declare the parameter using parenthesis similar to how you declare a dynamic array.

Passing to the procedure using ByRef means you are passing a reference of the array. So if you change the array in the procedure it will be changed when you return.

Note: When you use an array as a parameter it cannot use ByVal, it must use ByRef. You can pass the array using ByVal making the parameter a variant.

' https://excelmacromastery.com/
' Passes array to a Function
Public Sub PassToProc()
    Dim arr(0 To 5) As String
    ' Pass the array to function
    UseArray arr
End Sub

Public Function UseArray(ByRef arr() As String)
    ' Use array
    Debug.Print UBound(arr)
End Function

Returning the VBA Array from a Function

It is important to keep the following in mind. If you want to change an existing array in a procedure then you should pass it as a parameter using ByRef(see last section). You do not need to return the array from the procedure.

The main reason for returning an array is when you use the procedure to create a new one. In this case you assign the return array to an array in the caller. This array cannot be already allocated. In other words you must use a dynamic array that has not been allocated.

The following examples show this

' https://excelmacromastery.com/
Public Sub TestArray()

    ' Declare dynamic array - not allocated
    Dim arr() As String
    ' Return new array
    arr = GetArray

End Sub

Public Function GetArray() As String()

    ' Create and allocate new array
    Dim arr(0 To 5) As String
    ' Return array
    GetArray = arr

End Function

Using a Two-Dimensional VBA Array

The arrays we have been looking at so far have been one-dimensional arrays. This means the arrays are one list of items.

A two-dimensional array is essentially a list of lists. If you think of a single spreadsheet row as a single dimension then more than one column is two dimensional. In fact a spreadsheet is the equivalent of a two-dimensional array. It has two dimensions – rows and columns.

One small thing to note is that Excel treats a one-dimensional array as a row if you write it to a spreadsheet. In other words, the array arr(1 to 5) is equivalent to arr(1 to 1, 1 to 5) when writing values to the spreadsheet.

The following image shows two groups of data. The first is a one-dimensional layout and the second is two dimensional.

VBA Array Dimension

To access an item in the first set of data(1 dimensional) all you need to do is give the row e.g. 1,2, 3 or 4.

For the second set of data (two-dimensional), you need to give the row AND the column. So you can think of 1 dimensional being multiple columns and one row and two-dimensional as being multiple rows and multiple columns.

Note: It is possible to have more than two dimensions in an array. It is rarely required. If you are solving a problem using a 3+ dimensional array then there probably is a better way to do it.

You declare a two-dimensional array as follows:

Dim ArrayMarks(0 To 2,0 To 3) As Long

The following example creates a random value for each item in the array and the prints the values to the Immediate Window:

' https://excelmacromastery.com/
Public Sub TwoDimArray()

    ' Declare a two dimensional array
    Dim arrMarks(0 To 3, 0 To 2) As String

    ' Fill the array with text made up of i and j values
    Dim i As Long, j As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        For j = LBound(arrMarks, 2) To UBound(arrMarks, 2)
            arrMarks(i, j) = CStr(i) & ":" & CStr(j)
        Next j
    Next i

    ' Print the values in the array to the Immediate Window
    Debug.Print "i", "j", "Value"
    For i = LBound(arrMarks) To UBound(arrMarks)
        For j = LBound(arrMarks, 2) To UBound(arrMarks, 2)
            Debug.Print i, j, arrMarks(i, j)
        Next j
    Next i

End Sub

You can see that we use a second For loop inside the first loop to access all the items.

The output of the example looks like this:

VBA Arrays

How this Macro works is as follows:

  • Enters the i loop
  • i is set to 0
  • Entersj loop
  • j is set to 0
  • j is set to 1
  • j is set to 2
  • Exit j loop
  • i is set to 1
  • j is set to 0
  • j is set to 1
  • j is set to 2
  • And so on until i=3 and j=2

You may notice that LBound and UBound have a second argument with the value 2. This specifies that it is the upper or lower bound of the second dimension. That is the start and end location for j. The default value 1 which is why we do not need to specify it for the i loop.

Using the For Each Loop

Using a For Each is neater to use when reading from an array.

Let’s take the code from above that writes out the two-dimensional array

    ' Using For loop needs two loops
    Debug.Print "i", "j", "Value"
    For i = LBound(arrMarks) To UBound(arrMarks)
        For j = LBound(arrMarks, 2) To UBound(arrMarks, 2)
            Debug.Print i, j, arrMarks(i, j)
        Next j
    Next i

Now let’s rewrite it using a For each loop. You can see we only need one loop and so it is much easier to write:

    ' Using For Each requires only one loop
    Debug.Print "Value"
    Dim mark As Variant
    For Each mark In arrMarks
        Debug.Print mark
    Next mark

Using the For Each loop gives us the array in one order only – from LBound to UBound. Most of the time this is all you need.

Reading from a Range to the VBA Array

If you have read my previous post on Cells and Ranges then you will know that VBA has an extremely efficient way of reading from a Range of Cells to an Array and vice versa

' https://excelmacromastery.com/
Public Sub ReadToArray()

    ' Declare dynamic array
    Dim StudentMarks As Variant

    ' Read values into array from first row
    StudentMarks = Range("A1:Z1").Value

    ' Write the values back to the third row
    Range("A3:Z3").Value = StudentMarks

End Sub

The dynamic array created in this example will be a two dimensional array. As you can see we can read from an entire range of cells to an array in just one line.

The next example will read the sample student data below from C3:E6 of Sheet1 and print them to the Immediate Window:

' https://excelmacromastery.com/
Public Sub ReadAndDisplay()

    ' Get Range
    Dim rg As Range
    Set rg = ThisWorkbook.Worksheets("Sheet1").Range("C3:E6")

    ' Create dynamic array
    Dim StudentMarks As Variant

    ' Read values into array from sheet1
    StudentMarks = rg.Value

    ' Print the array values
    Debug.Print "i", "j", "Value"
    Dim i As Long, j As Long
    For i = LBound(StudentMarks) To UBound(StudentMarks)
        For j = LBound(StudentMarks, 2) To UBound(StudentMarks, 2)
            Debug.Print i, j, StudentMarks(i, j)
        Next j
    Next i

End Sub

VBA 2D Array

Sample Student data

VBA 2D Array Output

Output from sample data

As you can see the first dimension(accessed using i) of the array is a row and the second is a column. To demonstrate this take a look at the value 44 in E4 of the sample data. This value is in row 2 column 3 of our data. You can see that 44 is stored in the array at StudentMarks(2,3).

You can see more about using arrays with ranges in this YouTube video

How To Make Your Macros Run at Super Speed

If your macros are running very slow then you may find this section very helpful. Especially if you are dealing with large amounts of data. The following is a very well-kept secret in VBA

Updating values in arrays is exponentially faster than updating values in cells.

In the last section, you saw how we can easily read from a group of cells to an array and vice versa. If we are updating a lot of values then we can do the following:

1. Copy the data from the cells to an array.
2. Change the data in the array.
3. Copy the updated data from the array back to the cells.

For example, the following code would be much faster than the code below it:

' https://excelmacromastery.com/
Public Sub ReadToArray()

    ' Read values into array from first row
    Dim StudentMarks  As Variant
    StudentMarks = Range("A1:Z20000").Value

    Dim i As Long
    For i = LBound(StudentMarks) To UBound(StudentMarks)
        ' Update marks here
        StudentMarks(i, 1) = StudentMarks(i, 1) * 2
        '...
    Next i

    ' Write the new values back to the worksheet
    Range("A1:Z20000").Value = StudentMarks

End Sub
' https://excelmacromastery.com/
Sub UsingCellsToUpdate()
    
    Dim c As Variant
    For Each c In Range("A1:Z20000")
        c.Value = ' Update values here
    Next c
    
End Sub

Assigning from one set of cells to another is also much faster than using Copy and Paste:

' Assigning - this is faster
Range("A1:A10").Value = Range("B1:B10").Value

' Copy Paste - this is slower
Range("B1:B1").Copy Destination:=Range("A1:A10")

The following comments are from two readers who used arrays to speed up their macros

“A couple of my projects have gone from almost impossible and long to run into almost too easy and a reduction in time to run from 10:1.” – Dane

“One report I did took nearly 3 hours to run when accessing the cells directly — 5 minutes with arrays” – Jim

You can see more about the speed of Arrays compared to other methods in this YouTube video.

To see a comparison between Find, Match and Arrays it is worth checking out this post by Charles Williams.

Conclusion

The following is a summary of the main points of this post

  1. Arrays are an efficient way of storing a list of items of the same type.
  2. You can access an array item directly using the number of the location which is known as the subscript or index.
  3. The common error “Subscript out of Range” is caused by accessing a location that does not exist.
  4. There are two types of arrays: Static and Dynamic.
  5. Static is used when the length of the array is always the same.
  6. Dynamic arrays allow you to determine the length of an array at run time.
  7. LBound and UBound provide a safe way of find the smallest and largest subscripts of the array.
  8. The basic array is one dimensional. You can also have multidimensional arrays.
  9. You can only pass an array to a procedure using ByRef. You do this like this: ByRef arr() as long.
  10. You can return an array from a function but the array, it is assigned to, must not be currently allocated.
  11. A worksheet with its rows and columns is essentially a two-dimensional array.
  12. You can read directly from a worksheet range into a two-dimensional array in just one line of code.
  13. You can also write from a two-dimensional array to a range in just one line of code.

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try  The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

На чтение 24 мин. Просмотров 90.5k.

VBA Arrays

Дональд Кнут

Список настолько же силен, как и его самое слабое звено

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

Содержание

  1. Краткое руководство по массивам VBA
  2. Введение
  3. Быстрые заметки
  4. Что такое массивы и зачем они нужны?
  5. Типы массивов VBA
  6. Объявление массива
  7. Присвоение значений массиву
  8. Использование функций Array и Split
  9. Использование циклов с массивами
  10. Использование Erase
  11. ReDim с Preserve
  12. Сортировка массива
  13. Передача массива в Sub или функцию
  14. Возвращение массива из функции
  15. Двумерные массивы
  16. Чтение из диапазона ячеек в массив
  17. Как заставить ваши макросы работать на суперскорости
  18. Заключение

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

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

Введение

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

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

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

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

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

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

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

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

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

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

' Может хранить только 1 значение за раз
Dim Student1 As Integer
Student1 = 55

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

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

VBa Arrays

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

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

ImmediateWindow

ImmediateSampeText

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

Public Sub StudentMarks()

    With ThisWorkbook.Worksheets("Лист1")

        ' Объявите переменную для каждого студента
        Dim Student1 As Integer
        Dim Student2 As Integer
        Dim Student3 As Integer
        Dim Student4 As Integer
        Dim Student5 As Integer

        ' Читайте оценки студентов из ячейки
        Student1 = .Range("C2").Offset(1)
        Student2 = .Range("C2").Offset(2)
        Student3 = .Range("C2").Offset(3)
        Student4 = .Range("C2").Offset(4)
        Student5 = .Range("C2").Offset(5)

        ' Печать студенческих оценок
        Debug.Print "Оценки студентов"
        Debug.Print Student1
        Debug.Print Student2
        Debug.Print Student3
        Debug.Print Student4
        Debug.Print Student5

    End With

End Sub

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

VBA Arrays

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

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

Public Sub StudentMarksArr()

    With ThisWorkbook.Worksheets("Лист1")

        ' Объявите массив для хранения оценок для 5 студентов
        Dim Students(1 To 5) As Integer

        ' Читайте оценки учеников из ячеек C3: C7 в массив
        Dim i As Integer
        For i = 1 To 5
            Students(i) = .Range("C2").Offset(i)
        Next i

        ' Распечатывать оценки студентов из массива
        Debug.Print "Оценки студентов"
        For i = LBound(Students) To UBound(Students)
            Debug.Print Students(i)
        Next i

    End With

End Sub

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

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

 ' Объявляем переменные
        Dim Student As Integer
        Dim Country As String

  ' Объявляем массивы
        Dim Students(1 To 3) As Integer
        Dim Countries(1 To 3) As String

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

    ' присвоить значение переменной
        Student1 = .Cells(1, 1) 

    ' присваивать значение первому элементу в массиве
        Students(1) = .Cells(1, 1)

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

  ' Вывести значение переменной
        Debug.Print Student1

  ' Вывести значение первого студента в массиве
        Debug.Print Students(1)

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

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

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

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

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

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

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

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

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

Public Sub DecArrayStatic()

    ' Создать массив с местоположениями 0,1,2,3
    Dim arrMarks1(0 To 3) As Long

    ' По умолчанию от 0 до 3, то есть местоположения 0,1,2,3
    Dim arrMarks2(3) As Long

    ' Создать массив с местоположениями 1,2,3,4,5
    Dim arrMarks1(1 To 5) As Long

    ' Создать массив с местоположениями 2,3,4 'Это редко используется
    Dim arrMarks3(2 To 4) As Long

End Sub

VBA Arrays

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

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

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

Public Sub DecArrayDynamic()

    ' Объявить динамический массив
    Dim arrMarks() As Long

    ' Установите размер массива, когда вы будете готовы
    ReDim arrMarks(0 To 5)

End Sub

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

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

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

Public Sub AssignValue()

    ' Объявить массив с местоположениями 0,1,2,3
    Dim arrMarks(0 To 3) As Long

    ' Установите значение позиции 0
    arrMarks(0) = 5

    ' становите значение позиции 3
    arrMarks(3) = 46

    ' Это ошибка, так как нет местоположения 4
    arrMarks(4) = 99

End Sub

VBA Array 2

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

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

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

  Dim arr1 As Variant
    arr1 = Array("Апельсин", "Персик","Груша")

  Dim arr2 As Variant
    arr2 = Array(5, 6, 7, 8, 12)

Arrays VBA

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

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

 Dim s As String
    s = "Красный,Желтый,Зеленый,Синий"

    Dim arr() As String
    arr = Split(s, ",")

Arrays VBA

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

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

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

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

Public Sub ArrayLoops()

    ' Объявить массив
    Dim arrMarks(0 To 5) As Long

    ' Заполните массив случайными числами
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' Распечатайте значения в массиве
    Debug.Print "Место нахождения", "Значение"
    For i = LBound(arrMarks) To UBound(arrMarks)
        Debug.Print i, arrMarks(i)
    Next i

End Sub

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

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

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

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

 For Each mark In arrMarks
        ' Не изменит значение массива
        mark = 5 * Rnd
    Next mark

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

  Dim mark As Variant
    For Each mark In arrMarks
        Debug.Print mark
    Next mark

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

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

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

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

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

Public Sub EraseStatic()

    ' Объявить массив
    Dim arrMarks(0 To 3) As Long

    ' Заполните массив случайными числами
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' ВСЕ ЗНАЧЕНИЯ УСТАНОВЛЕНЫ НА НОЛЬ
    Erase arrMarks

    ' Распечатайте значения - там все теперь ноль
    Debug.Print "Место нахождения", "Значение"
    For i = LBound(arrMarks) To UBound(arrMarks)
        Debug.Print i, arrMarks(i)
    Next i

End Sub

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

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

Public Sub EraseDynamic()

    ' Объявить массив
    Dim arrMarks() As Long
    ReDim arrMarks(0 To 3)

    ' Заполните массив случайными числами
    Dim i As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        arrMarks(i) = 5 * Rnd
    Next i

    ' arrMarks теперь освобожден. Места не существуют.
    Erase arrMarks

End Sub

ReDim с Preserve

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

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

Sub UsingRedim()

    Dim arr() As String
    
    ' Установить массив в слоты от 0 до 2
    ReDim arr(0 To 2)
    arr(0) = "Яблоко"
    
    ' Массив с яблоком теперь удален
    ReDim arr(0 To 3)

End Sub

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

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

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

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

Sub UsingRedimPreserve()

    Dim arr() As String
    
    ' Установить массив в слоты от 0 до 1
    ReDim arr(0 To 2)
    arr(0) = "Яблоко"
    arr(1) = "Апельсин"
    arr(2) = "Груша"
    
    ' Изменение размера и сохранение исходного содержимого
    ReDim Preserve arr(0 To 5)

End Sub

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

VBA Preserve

VBA Preserve

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

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

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

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

Sub Preserve2D()

    Dim arr() As Long
    
    ' Установите начальный размер
    ReDim arr(1 To 2, 1 To 5)
    
    ' Изменить размер верхнего измерения
    ReDim Preserve arr(1 To 2, 1 To 10)

End Sub

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

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

Sub Preserve2DError()

    Dim arr() As Long
    
    ' Установите начальный размер
    ReDim arr(1 To 2, 1 To 5)
    
    ' Ошибка «Вне диапазона»
    ReDim Preserve arr(1 To 5, 1 To 5)

End Sub

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

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

Sub Preserve2DRange()

    Dim arr As Variant
    
    ' Назначить диапазон массиву
    arr = Sheet1.Range("A1:A5").Value
    
    ' Preserve будет работать только на верхней границе
    ReDim Preserve arr(1 To 5, 1 To 7)

End Sub

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

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

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

Sub QuickSort(arr As Variant, first As Long, last As Long)
  
  Dim vCentreVal As Variant, vTemp As Variant
  
  Dim lTempLow As Long
  Dim lTempHi As Long
  lTempLow = first
  lTempHi = last
  
  vCentreVal = arr((first + last) / 2)
  Do While lTempLow <= lTempHi
  
    Do While arr(lTempLow) < vCentreVal And lTempLow < last
      lTempLow = lTempLow + 1
    Loop
    
    Do While vCentreVal < arr(lTempHi) And lTempHi > first
      lTempHi = lTempHi - 1
    Loop
    
    If lTempLow <= lTempHi Then
    
        ' Поменять значения
        vTemp = arr(lTempLow)

        arr(lTempLow) = arr(lTempHi)
        arr(lTempHi) = vTemp
      
        ' Перейти к следующим позициям
        lTempLow = lTempLow + 1
        lTempHi = lTempHi - 1
      
    End If
    
  Loop
  
  If first < lTempHi Then QuickSort arr, first, lTempHi
  If lTempLow < last Then QuickSort arr, lTempLow, last
  
End Sub

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

Sub TestSort()

    ' Создать временный массив
    Dim arr() As Variant
    arr = Array("Банан", "Дыня", "Персик", "Слива", "Яблоко")
  
    ' Сортировать массив
    QuickSort arr, LBound(arr), UBound(arr)

    ' Печать массива в Immediate Window(Ctrl + G)
    Dim i As Long
    For i = LBound(arr) To UBound(arr)
        Debug.Print arr(i)
    Next i

End Sub

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

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

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

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

' Передает массив в функцию
Public Sub PassToProc()
    Dim arr(0 To 5) As String
    ' Передать массив в функцию
    UseArray arr
End Sub

Public Function UseArray(ByRef arr() As String)
    ' Использовать массив
    Debug.Print UBound(arr)
End Function

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

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

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

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

Public Sub TestArray()

    ' Объявить динамический массив - не выделен
    Dim arr() As String
    ' Возврат нового массива
    arr = GetArray

End Sub

Public Function GetArray() As String()

    ' Создать и выделить новый массив
    Dim arr(0 To 5) As String
    ' Возвращаемый массив
    GetArray = arr

End Function

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

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

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

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

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

VBA Array Dimension

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

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

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

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

Dim ArrayMarks(0 To 2, 0 To 3) As Long

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

Public Sub TwoDimArray()

    ' Объявить двумерный массив
    Dim arrMarks(0 To 3, 0 To 2) As String

    ' Заполните массив текстом, состоящим из значений i и j
    Dim i As Long, j As Long
    For i = LBound(arrMarks) To UBound(arrMarks)
        For j = LBound(arrMarks, 2) To UBound(arrMarks, 2)
            arrMarks(i, j) = CStr(i) & ":" & CStr(j)
        Next j
    Next i

    ' Вывести значения в массиве в Immediate Window
    Debug.Print "i", "j", "Знаечние"
    For i = LBound(arrMarks) To UBound(arrMarks)
        For j = LBound(arrMarks, 2) To UBound(arrMarks, 2)
            Debug.Print i, j, arrMarks(i, j)
        Next j
    Next i

End Sub

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

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

VBA Arrays

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

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

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

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

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

 ' Для цикла For необходимо два цикла
    Debug.Print "i", "j", "Значение"
    For i = LBound(arrMarks) To UBound(arrMarks)
        For j = LBound(arrMarks, 2) To UBound(arrMarks, 2)
            Debug.Print i, j, arrMarks(i, j)
        Next j
    Next i

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

 ' Использование For Each требует только одного цикла
    Debug.Print "Значение"
    Dim mark As Variant
    For Each mark In arrMarks
        Debug.Print mark
    Next mark

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

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

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

Public Sub ReadToArray()

    ' Объявить динамический массив
    Dim StudentMarks As Variant

    ' Считать значения в массив из первой строки
    StudentMarks = Range("A1:Z1").Value

    ' Запишите значения обратно в третий ряд
    Range("A3:Z3").Value = StudentMarks

End Sub

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

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

Public Sub ReadAndDisplay()

    ' Получить диапазон
    Dim rg As Range
    Set rg = ThisWorkbook.Worksheets("Лист1").Range("C3:E6")

    ' Создать динамический массив
    Dim StudentMarks As Variant

    ' Считать значения в массив из листа 1
    StudentMarks = rg.Value

    ' Вывести значения массива
    Debug.Print "i", "j", "Значение"
    Dim i As Long, j As Long
    For i = LBound(StudentMarks) To UBound(StudentMarks)
        For j = LBound(StudentMarks, 2) To UBound(StudentMarks, 2)
            Debug.Print i, j, StudentMarks(i, j)
        Next j
    Next i

End Sub

VBA 2D Array

VBA 2D Array Output

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

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

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

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

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

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

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

Public Sub ReadToArray()

    ' Считать значения в массив из первой строки
    Dim StudentMarks  As Variant
    StudentMarks = Range("A1:Z20000").Value

    Dim i As Long
    For i = LBound(StudentMarks) To UBound(StudentMarks)
        ' Обновление отметок здесь
        StudentMarks(i, 1) = StudentMarks(i, 1) * 2
        '...
    Next i

    ' Запишите новые значения обратно на лист
    Range("A1:Z20000").Value = StudentMarks

End Sub
Sub UsingCellsToUpdate()
    
    Dim c As Variant
    For Each c In Range("A1:Z20000")
        c.Value = ' Обновите значения здесь
    Next c
    
End Sub

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

' Назначение - быстрее
Range("A1:A10").Value = Range("B1:B10").Value

' Копировать Вставить - медленнее
Range("B1:B1").Copy Destination:=Range("A1:A10")

Заключение

Ниже приводится краткое изложение основных моментов этой статьи.

  1. Массивы — это эффективный способ хранения списка элементов одного типа.
  2. Вы можете получить доступ к элементу массива напрямую, используя номер местоположения, который известен как индекс.
  3. Распространенная ошибка «Индекс вне диапазона» вызвана доступом к несуществующему местоположению.
  4. Существует два типа массивов: статический и динамический.
  5. Статический используется, когда размер массива всегда одинаков.
  6. Динамические массивы позволяют вам определять размер массива во время выполнения.
  7. LBound и UBound обеспечивают безопасный способ поиска самых маленьких и самых больших подписок массива.
  8. Основной массив является одномерным. Есть еще многомерные массивы.
  9. Чтобы только передать массив в процедуру, используйте ByRef. Вы делаете это так: ByRef arr() as long.
  10. Вы можете вернуть массив из функции, но массив, которому он назначен, не должен быть выделен в данный момент.
  11. Рабочий лист с его строками и столбцами по сути является двумерным массивом.
  12. Вы можете читать непосредственно из диапазона листа в двухмерный массив всего за одну строку кода.
  13. Вы также можете записать из двумерного массива в диапазон всего за одну строку кода.

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

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

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

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

Public Massiv1(9) As Integer

Dim Massiv2(1 To 9) As String

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

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

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

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

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

Public Massiv1(3, 6) As Integer

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

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

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

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

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

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

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

Public Massiv1() As Integer

Dim Massiv2() As String

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

Public Massiv1() As Integer

Dim Massiv2() As String

ReDim Massiv1(1 To 20)

ReDim Massiv2(3, 5, 4)

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

Dim Massiv1() as Variant, x As Integer

x = 20

ReDim Massiv1(1 To x)

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

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

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

Dim Massiv1() As String

операторы

ReDim Massiv1(5, 2, 3)

операторы

ReDim Preserve Massiv1(5, 2, 7)

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

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

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

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

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

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

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

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

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

Функция Array

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

Sub Test1()

Dim a() As Variant

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

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

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

End Sub

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

Функция LBound

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

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

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

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

Функция UBound

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

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

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

Sub Test2()

Dim a(2 To 53) As String

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

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

End Sub

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

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

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

Sub Test3()

Dim a() As Variant, i As Long

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

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

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

    Next

End Sub

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

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

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

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

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

операторы

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

ReDim Massiv2(2, 5, 3)

операторы

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

Erase Massiv1

Erase Massiv2

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

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

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

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

Dim Massiv() As Double

операторы

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

ReDim Massiv(5, 6, 8)

операторы

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

ReDim Massiv(5, 6, 8)


In this Article

  • VBA Array Quick Sheet
    • Arrays
  • VBA Array Quick Examples
  • Array Benefits? – Speed!
  • Create / Declare an Array (Dim)
    • Static Array
    • Dynamic Array
    • ReDim vs. ReDim Preserve
    • Declaring Arrays Simplified
  • Set Array Values
    • Get Array Value
  • Assign Range to Array
    • Output Array to Range
  • 2D / Multi-Dimensional Arrays
  • Multi-Dimensional Array Examples
    • 1D Array Example
    • 2D Array Example
    • 3D Array Example
  • Array Length / Size
    • UBound and LBound Functions
    • Array Length Function
  • Loop Through Array
    • For Each Array Loop
    • Loop Through 2D Array
  • Other Array Tasks
    • Clear Array
    • Count Array
    • Remove Duplicates
    • Filter
    • IsArray Function
    • Join Array
    • Split String into Array
    • Const Array
    • Copy Array
    • Transpose
    • Function Return Array
  • Using Arrays in Access VBA

In VBA, an Array is a single variable that can hold multiple values.  Think of an array like a range of cells: each cell can store a value. Arrays can be one-dimensional (think of a single column), two-dimensional (think of multiple rows & columns), or multi-dimensional.  Array values can be accessed by their position (index number) within the array.

VBA Array Quick Sheet

Arrays

Create

Dim arr(1 To 3) As Variant
arr(1) = “one”
arr(2) = “two”
arr(3) = “three”

Create From Excel

Dim arr(1 To 3) As Variant
Dim cell As Range, i As Integer
i = LBound(arr)
For
Each cell In Range(“A1:A3”)
i = i + 1
arr(i) = cell.value
Next cell

Read All Items

Dim i as Long
For i = LBound(arr) To UBound(arr)
MsgBox arr(i)
Next i

Array to String

Dim sName As String
sName = Join(arr, “:”)

Increase Size

ReDim Preserve arr(0 To 100)

VBA Array Quick Examples

Let’s look at a full example before we dive into specifics:

Sub ArrayExample()
    Dim strNames(1 to 4) as String

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    strNames(3) = "Neema"
    strNames(4) = "Jose"

    msgbox strNames(3)
End Sub

Here we’ve created the one-dimensional string array: strNames with size four (can hold four values) and assigned the four values. Last we display the 3rd value in a Message Box.

In this case, the benefit of using an Array is small: only one variable declaration is required instead of four.

However, let’s look at an example that will show the true power of an array:

Sub ArrayExample2()
    Dim strNames(1 To 60000) As String
    Dim i As Long

    For i = 1 To 60000
        strNames(i) = Cells(i, 1).Value
    Next i
End Sub

Here we’ve created an Array that can hold 60,000 values and we’ve quickly populated the array from Column A of a worksheet.

Array Benefits? – Speed!

You might think of Arrays similar to Excel worksheets:

  • Each cell (or item in an array) can contain its own value
  • Each cell (or item in an array) can be accessed by its row & column position.
    • Worksheet Ex.  cells(1,4).value = “Row 1, Column 4”
    • Array Ex.  arrVar(1,4) = “Row 1, Column 4”

So why bother with Arrays?  Why not just read and write values directly to cells in Excel?  One word: Speed!

Reading / Writing to Excel cells is a slow process. Working with Arrays is much faster!

Create / Declare an Array (Dim)

Note: Arrays can have multiple “dimensions”. To keep things simple, we will start by only working with one-dimensional arrays. Later in the tutorial we will introduce you to multiple-dimension arrays.

Static Array

Static Arrays are arrays that cannot change size. Conversely, Dynamic Arrays can change size.  They are declared slightly differently. First, let’s look at static arrays.

Note: If your array won’t change in size, use a static array.

Declaring a static array variable is very similar to declaring a regular variable, except you must define the size of the array. There are several different ways to set the size of an array.

You can explicitly declare the start and end positions of an array:

Sub StaticArray1()

    'Creates array with positions 1,2,3,4
    Dim arrDemo1(1 To 4) As String
    
    'Creates array with positions 4,5,6,7
    Dim arrDemo2(4 To 7) As Long
    
    'Creates array with positions 0,1,2,3
    Dim arrDemo3(0 To 3) As Long

End Sub

Or you can enter only the array size:

Sub StaticArray2()

    'Creates array with positions 0,1,2,3
    Dim arrDemo1(3) As String

End Sub

Important! Notice that by default, Arrays start at position 0.  So Dim arrDemo1(3) creates an array with positions 0,1,2,3.

You can declare Option Base 1 at the top of your module so that the array starts at position 1 instead:

Option Base 1

Sub StaticArray3()

    'Creates array with positions 1,2,3
    Dim arrDemo1(3) As String

End Sub

However, I find that it’s much easier (and less confusing) to just explicitly declare the start and end positions of arrays.

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!

automacro

Learn More

Dynamic Array

Dynamic Arrays are arrays whose size can be changed (or whose size does not need to be defined).

There are two ways to declare a Dynamic Array.

Variant Arrays

The first way to declare a Dynamic Array is by setting the array to type Variant.

Dim arrVar() As Variant

With a Variant Array, you do not need to define the array size. The size will automatically adjust.  Just remember that the Array starts with position 0 (unless you add Option Base 1 to the top of your module)

Sub VariantArray()
    Dim arrVar() As Variant
    
    'Define Values (Size = 0,1,2,3)
    arrVar = Array(1, 2, 3, 4)
    
    'Change Values (Size = 0,1,2,3,4)
    arrVar = Array("1a", "2a", "3a", "4a", "5a")

    'Output Position 4 ("5a")
    MsgBox arrVar(4)

End Sub

Non-Variant Dynamic Arrays

With non-variant arrays, you must define the array size before assigning values to the array. However, the process to create the array is slightly different:

Sub DynamicArray1()
    Dim arrDemo1() As String

    'Resizes array with positions 1,2,3,4
    ReDim arrDemo1(1 To 4)
    
End Sub

First you declare the array, similar to the static array, except you omit the array size:

Dim arrDemo1() As String

Now when you want to set the array size you use the ReDim command to size the array:

'Resizes array with positions 1,2,3,4
ReDim arrDemo1(1 To 4)

ReDim resizes the array. Read below for the difference between ReDim and ReDim Preserve.

ReDim vs. ReDim Preserve

When you use the ReDim command you clear all existing values from the array.  Instead you can use ReDim Preserve to preserve array values:

'Resizes array with positions 1,2,3,4 (Preserving existing values)
ReDim Preserve arrDemo1(1 To 4)

Declaring Arrays Simplified

You might be feeling overwhelmed after reading everything above. To keep things simple, we will mostly work with static arrays for the rest of the article.

VBA Programming | Code Generator does work for you!

Set Array Values

Setting array values is very easy.

With a static array, you must define each position of the array, one at a time:

Sub ArrayExample()
    Dim strNames(1 to 4) as String

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    strNames(3) = "Neema"
    strNames(4) = "Jose"
End Sub

With a Variant Array you can define the entire array with one line (only practical for small arrays):

Sub ArrayExample_1Line()
    Dim strNames() As Variant

    strNames = Array("Shelly", "Steve", "Neema", "Jose")

End Sub

If you attempt to define a value for an array location that does not exist, you will receive a Subscript Out of Range error:

strNames(5) = "Shannon"

vba set array value

In the ‘Assign Range to Array’ section Below we’ll show you how to use a loop to quickly assign large numbers of values to arrays.

Get Array Value

You can fetch array values the same way.  In the example below we will write array values to cells:

    Range("A1").Value = strNames(1)
    Range("A2").Value = strNames(2)
    Range("A3").Value = strNames(3)
    Range("A4").Value = strNames(4)

Assign Range to Array

To assign a Range to an Array you can use a loop:

Sub RangeToArray()
    Dim strNames(1 To 60000) As String
    Dim i As Long

    For i = 1 To 60000
        strNames(i) = Cells(i, 1).Value
    Next i
End Sub

This will loop through cells A1:A60000, assigning the cell values to the array.

Output Array to Range

Or you can use a loop to assign an array to a range:

    For i = 1 To 60000
        Cells(i, 1).Value = strNames(i)
    Next i

This will do the reverse: assign array values to cells A1:A60000

2D / Multi-Dimensional Arrays

So far we’ve worked exclusively with single-dimensional (1D) arrays.  However, arrays can have up to 32 dimensions.

Think of a 1D array like a single row or column of Excel cells, a 2D array like an entire Excel worksheet with multiple rows and columns, and a 3D array is like an entire workbook, containing multiple sheets each containing multiple rows and columns (You could also think of a 3D array as like a Rubik’s Cube).

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Multi-Dimensional Array Examples

Now let’s demonstrate examples of working with arrays of different dimensions.

1D Array Example

This procedure combines the previous array examples into one procedure, demonstrating how you might use arrays in practice.

Sub ArrayEx_1d()
    Dim strNames(1 To 60000) As String
    Dim i As Long
 
    'Assign Values to Array
    For i = 1 To 60000
        strNames(i) = Cells(i, 1).Value
    Next i
    
    'Output Array Values to Range
    For i = 1 To 60000
        Sheets("Output").Cells(i, 1).Value = strNames(i)
    Next i
End Sub

2D Array Example

This procedure contains an example of a 2D array:

Sub ArrayEx_2d()
    Dim strNames(1 To 60000, 1 To 10) As String
    Dim i As Long, j As Long
 
    'Assign Values to Array
    For i = 1 To 60000
        For j = 1 To 10
            strNames(i, j) = Cells(i, j).Value
        Next j
    Next i
    
    'Output Array Values to Range
    For i = 1 To 60000
        For j = 1 To 10
            Sheets("Output").Cells(i, j).Value = strNames(i, j)
        Next j
    Next i
End Sub

3D Array Example

This procedure contains an example of a 3D array for working with multiple sheets:

Sub ArrayEx_3d()
    Dim strNames(1 To 60000, 1 To 10, 1 To 3) As String
    Dim i As Long, j As Long, k As Long
 
    'Assign Values to Array
    For k = 1 To 3
        For i = 1 To 60000
            For j = 1 To 10
                strNames(i, j, k) = Sheets("Sheet" & k).Cells(i, j).Value
            Next j
        Next i
    Next k
    
    'Output Array Values to Range
    For k = 1 To 3
        For i = 1 To 60000
            For j = 1 To 10
                Sheets("Output" & k).Cells(i, j).Value = strNames(i, j, k)
            Next j
        Next i
    Next k
End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Array Length / Size

So far, we’ve introduced you to the different types of arrays and taught you how to declare the arrays and get/set array values. Next we will focus on other necessary topics for working with arrays.

UBound and LBound Functions

The first step to getting the length / size of an array is using the UBound and LBound functions to get the upper and lower bounds of the array:

Sub UBoundLBound()
    Dim strNames(1 To 4) As String
    
    MsgBox UBound(strNames)
    MsgBox LBound(strNames)
End Sub

Subtracting the two (and adding 1) will give you the length:

GetArrLength = UBound(strNames) - LBound(strNames) + 1

Array Length Function

Here is a function to get a single-dimension array’s length:

Public Function GetArrLength(a As Variant) As Long
   If IsEmpty(a) Then
      GetArrLength = 0
   Else
      GetArrLength = UBound(a) - LBound(a) + 1
   End If
End Function

Need to calculate the size of a 2D array? Check out our tutorial: Calculate Size of Array.

Loop Through Array

There are two ways to loop through an array.  The first loops through the integers corresponding to the number positions of the array. If you know the array size you can specify it directly:

Sub ArrayExample_Loop1()
    Dim strNames(1 To 4) As String
    Dim i As Long

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    strNames(3) = "Neema"
    strNames(4) = "Jose"
    
    For i = 1 To 4
        MsgBox strNames(i)
    Next i
End Sub

However, if you don’t know the array size (if the array is dynamic), you can use the LBound and UBound functions from the previous section:

Sub ArrayExample_Loop2()
    Dim strNames(1 To 4) As String
    Dim i As Long

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    strNames(3) = "Neema"
    strNames(4) = "Jose"
    
    For i = LBound(strNames) To UBound(strNames)
        MsgBox strNames(i)
    Next i
End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

For Each Array Loop

The second method is with a For Each Loop. This loops through each item in the array:

Sub ArrayExample_Loop3()
    Dim strNames(1 To 4) As String
    Dim Item

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    strNames(3) = "Neema"
    strNames(4) = "Jose"
    
    For Each Item In strNames
        MsgBox Item
    Next Item
End Sub

The For Each Array Loop will work with multi-dimensional arrays in addition to one-dimensional arrays.

Loop Through 2D Array

You can also use the UBound and LBound functions to loop through a multi-dimensional array as well. In this example we will loop through a 2D array.  Notice that the UBound and LBound Functions allow you to specify which dimension of the array to find the upper and lower bounds (1 for first dimension, 2 for second dimension).

Sub ArrayExample_Loop4()
    Dim strNames(1 To 4, 1 To 2) As String
    Dim i As Long, j As Long

    strNames(1, 1) = "Shelly"
    strNames(2, 1) = "Steve"
    strNames(3, 1) = "Neema"
    strNames(4, 1) = "Jose"
    
    strNames(1, 2) = "Shelby"
    strNames(2, 2) = "Steven"
    strNames(3, 2) = "Nemo"
    strNames(4, 2) = "Jesse"
    
    For j = LBound(strNames, 2) To UBound(strNames, 2)
        For i = LBound(strNames, 1) To UBound(strNames, 1)
            MsgBox strNames(i, j)
        Next i
    Next j
End Sub

Other Array Tasks

Clear Array

To clear an entire array, use the Erase Statement:

Erase strNames

Usage Example:

Sub ArrayExample()
    Dim strNames(1 to 4) as String

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    strNames(3) = "Neema"
    strNames(4) = "Jose"

    Erase strNames
End Sub

Alternatively, you can also ReDim the array to resize it, clearing part of the array:

ReDim strNames(1 to 2)

This resizes the array to size 2, deleting positions 3 and 4.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Count Array

You can count the number of positions in each dimension of  an array using the UBound and LBound Functions (discussed above).

You can also count the number of entered items (or items that meet certain criteria) by looping through the array.

This example will loop through an array of objects, and count the number of non-blank strings found in the array:

Sub ArrayLoopandCount()
    Dim strNames(1 To 4) As String
    Dim i As Long, n As Long

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    
    For i = LBound(strNames) To UBound(strNames)
        If strNames(i) <> "" Then
            n = n + 1
        End If
    Next i
    
    MsgBox n & " non-blank values found."
End Sub

Remove Duplicates

At some point, you may want to remove duplicates from an Array. Unfortunately, VBA does not have a built-in feature to do this. However, we’ve written a function to remove duplicates from an Array (it’s too long to include in this tutorial, but visit the link to learn more).

Filter

The VBA Filter Function allows you to Filter an Array. It does so by creating a new array with only the filtered values.  Below is a quick example, but make sure to read the article for more examples for different needs.

Sub Filter_Match()
 
    'Define Array
    Dim strNames As Variant
    strNames = Array("Steve Smith", "Shannon Smith", "Ryan Johnson")
 
    'Filter Array
    Dim strSubNames As Variant
    strSubNames = Filter(strNames, "Smith")
    
    'Count Filtered Array
    MsgBox "Found " & UBound(strSubNames) - LBound(strSubNames) + 1 & " names."
 
End Sub

IsArray Function

You can test if a variable is an array using the IsArray Function:

Sub IsArrayEx()

    'Creates array with positions 1,2,3
    Dim arrDemo1(3) As String
    
    'Creates regular string variable
    Dim str As String
    
    MsgBox IsArray(arrDemo1)
    MsgBox IsArray(str)

End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Join Array

You can quickly “join” an entire array together with the Join Function:

Sub Array_Join()
    Dim strNames(1 To 4) As String
    Dim joinNames As String

    strNames(1) = "Shelly"
    strNames(2) = "Steve"
    strNames(3) = "Neema"
    strNames(4) = "Jose"
    
    joinNames = Join(strNames, ", ")
    MsgBox joinNames
End Sub

Split String into Array

The VBA Split Function will split a string of text into an array containing values from the original string. Let’s look at an example:

Sub Array_Split()
    Dim Names() As String
    Dim joinedNames As String
    
    joinedNames = "Shelly,Steve,Nema,Jose"
    Names = Split(joinedNames, ",")

    MsgBox Names(1)
End Sub

Here we split this string of text “Shelly,Steve,Nema,Jose” into an array (size 4) using the a comma delimiter (,”).

Const Array

An Array cannot be declared as a constant in VBA. However, you can work around this by creating a function to use as an Array:

' Define ConstantArray
Function ConstantArray()
    ConstantArray = Array(4, 12, 21, 100, 5)
End Function

' Retrive ConstantArray Value
Sub RetrieveValues()
    MsgBox ConstantArray(3)
End Sub

Copy Array

There is no built-in way to copy an Array using VBA. Instead you will need to use a loop to assign the values from one array to another.

Sub CopyArray()

    Dim Arr1(1 To 100) As Long
    Dim Arr2(1 To 100) As Long
    Dim i As Long
    
    'Create Array1
    For i = 1 To 100
        Arr1(i) = i
    Next i
    
    'CopyArray1 to Array2
    For i = 1 To 100
        Arr2(i) = Arr1(i)
    Next i
    
    MsgBox Arr2(74)

End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Transpose

There is no built-in VBA function to allow you to Transpose an array. However, we’ve written a function to Transpose a 2D Array. Read the article to learn more.

Function Return Array

A common question VBA developers have is how to create a function that returns an array. I think most of the difficulties are resolved by using Variant Arrays. We’ve written an article on the topic: VBA Function Return Array.

Using Arrays in Access VBA

Most of the Array examples above work exactly the same in Access VBA as they do in Excel VBA.   The one major difference is that when you wish to populate an array using Access data, you would need to loop through the RecordSet object rather than the Range object.

Sub RangeToArrayAccess()
   On Error Resume Next
   Dim strNames() As String
   Dim i As Long
   Dim iCount As Long
   Dim dbs As Database
   Dim rst As Recordset
   Set dbs = CurrentDb
   Set rst = dbs.OpenRecordset("tblClients", dbOpenDynaset)
   With rst
      .MoveLast
      .MoveFirst
      iCount = .RecordCount
      ReDim strNames(1 To iCount)
      For i = 1 To iCount
         strNames(i) = rst.Fields("ClientName")
         .MoveNext
      Next i
   End With
   rst.Close
   Set rst = Nothing
   Set dbs = Nothing
End Sub

Массивы используются в большинстве языков программирования и 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, т.е. через индекс элемента.

If you’ve been working with (or learning) Visual Basic for Applications, you’re probably aware of the importance of having a solid knowledge of certain topics that influence data storage and manipulation. I’ve written detailed and comprehensive tutorials about several of these topics, including the following 2:

  • Declare Variables In VBA For Excel: The How-To Guide.
  • Excel VBA Data Types: The Complete Guide.

Excel VBA tutorial about arraysIn this VBA tutorial, I focus on a topic that is closely related to the above:

Excel VBA arrays.

You’ll be glad to know that, if you already have a basic knowledge of variables and data types (I cover these topics in the blog posts I link to above), you already have a good base knowledge that will help you understand and master the topic of arrays.

After all, arrays are (in the end) variables. Therefore, working with VBA arrays is (to a certain extent) very similar to working with regular variables. Arrays have, however, certain special characteristics and features that differ from those regular variables.

You might be wondering why should you bother learning about Excel VBA arrays if you already have a good knowledge of regular variables.

To put it simply:

You should learn to work with Excel VBA arrays because, among other benefits (as listed in Excel 2016 VBA and Macros), they:

  • Allow you to group related data and, more generally, make data manipulation easier.
  • Help you ease the process of getting information from data.
  • Can make your code more readable and easier to maintain.
  • Allow you to increase the speed of your VBA applications.

An indication of the power of VBA arrays is provided by author Richard Mansfield. In Mastering VBA for Microsoft Office 2016, Mansfield describes arrays as “kind of super variable[s]” or “variable[s] on steroids”.

My purpose with this VBA tutorial is to provide you with a comprehensive and detailed introduction to the topic of Excel VBA arrays that allows you to start using arrays now. The following table of contents lists the main sections of this blog post. Please feel free to use it to easily navigate to the topic of your interest.

This Excel VBA Array Tutorial is accompanied by an Excel workbook containing the data and macros I use in the examples below. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Now:

Even though I’ve already provided a basic description of arrays in the introduction above, let’s start by diving deeper into the topic of…

What Is An Excel VBA Array

According to the Microsoft Dev Center, an array is:

A set of sequentially indexed elements having the same intrinsic data type. Each element of an array has a unique identifying index number. Changes made to one element of an array don’t affect the other elements.

In Excel VBA Programming For Dummies, Excel guru John Walkenbach provides a broader definition of array by stating that:

An array is a group of variables that share a name.

These 2 definitions provide a good idea of the basic characteristics of a VBA array that you need to understand for purposes of this tutorial. These main characteristics of a VBA array are:

  • For purposes of Visual Basic for Applications an array is, basically, a group of variables.
  • The group of variables that make up an array have (i) the same name, and (ii) the same data type.
  • The variables that compose an array are sequentially indexed. Therefore, each array element has a unique identifying index number.
  • You can make changes to a particular array element without changing the other elements.

    At the same time, and as explained in Mastering VBA for Microsoft Office 2016, you can work with the whole array (all of its elements) at once

Let’s move on to one of the most important topics of this tutorial:

How To Declare An Excel VBA Array

As explained in Excel VBA Programming For Dummies, you must always declare an array before using it.

From a general perspective, you declare arrays the same way you declare other variables. This is because an array is itself a variable.

As I explain in my separate VBA tutorial about declaring variables, you can generally use 4 keywords to declare a variable explicitly:

  1. Dim.
  2. Static.
  3. Public.
  4. Private.

You can generally use those same 4 statements to declare an array. Therefore, if you understand how to declare variables in VBA, you already have the basic knowledge that is required to declare arrays.

Another important similarity is that when declaring arrays, you can specify their data type (just as you do with variables).

At a very basic level, there’s 1 main difference between declaring a regular (scalar) variable and an array:

When you declare an array, you usually have to specify the size of the array. When you declare a scalar variable (not an array), you don’t have to specify its size.

As a consequence of the above, the 4 elements you must consider when building a statement to declare an array are the following:

  • Element #1: The keyword you’re using to declare the array.

    As I mention above, you can use 4 different keywords for these purposes: (i) Dim, (ii) Static, (iii) Public and (iv) Private.

  • Element #2: The name of the array.
  • Element #3: The size of the array.

    The following sections explain how this item differs depending on whether you’re declaring a fixed or a dynamic Array.

  • Element #4: The data type for the array.

Therefore, a statement that declares an array using the items above has (roughly) the following structure:

Declaring_Keyword Array_Name([Array_Size]) [As Data_Type]

Items within square brackets ([ ]) are optional. Within this statement:

  • Item #1 (Declaring_Keyword) is 1 of the 4 keywords that you can use to declare an array (Dim, Static, Public or Private).
  • Item #2 (Array_Name) is the name of the array.
  • Item #3 (Array_Size) is the size of the array. This item is usually referred to as the array or dimension subscripts.

    The following sections focus on how you work with this particular item depending on whether you’re declaring a fixed or a dynamic Array. Whether the array is fixed or dynamic determines whether the Array_Size is optional or mandatory.

  • Item #4 (Data_Type): is the data type for the array.

    This item is optional.

Items #1 (Declaring_Keyword), #2 (Array_Name) and #4 (Data_Type) are substantially the same as those that you use when declaring variables in VBA.

Item #3 (Array_Size), as anticipated above, is the basic difference between declaring a scalar variable and an array. As a result of this root difference between variable and array declaration, there are 4 additional topics that you must consider when declaring an array (vs. when declaring a scalar variable):

  • Topic #1: Array size and memory requirements.
  • Topic #2: One-dimensional vs. multidimensional arrays.
  • Topic #3: Fixed vs. dynamic arrays.
  • Topic #4: Lower array bounds.

The following sections explain each of these topics. Let’s start by taking a look at:

Array Size, Data Types And Memory Requirements

As I explain above, you can specify the data type of an array when you declare it. For general purposes, the explanations and comments about the topic that I provide in this tutorial are applicable.

As a consequence of this, whenever you don’t declare the data type for an array, Visual Basic for Applications uses the default data type. This default data type is Variant. However, you may want to declare arrays using a different data type (other than Variant).

The main reason for this is that there’s an inverse relationship between execution speed and the amount of bytes used by the relevant data. The more bytes your data uses, the slower the execution of your VBA application. In practice, this may not be a big issue, assuming that you’re working on a computer with enough available memory. However, if you work with very large (particularly multidimensional) arrays, you may notice a difference in performance.

An exception to this rule is if you want the array to hold different data types. In such a case, the array data type must be Variant. This is because, as explained by Richard Mansfield in Mastering VBA for Microsoft Office 2016:

An array with the Variant data type can store multiple subtypes of data.

When deciding how to proceed, remember that different data types have different nominal allocation requirements. The following table provides a basic idea of how many bytes of memory are usually required by several of the main VBA data types:

Data Type of Element Bytes
Variant (numeric) 16
Variant (string) 22 + string requirement
Byte 1
Boolean 2
Currency 8
Date 8
Double 8
Integer 2
Long 4
Object 4
Single 4
String (variable-length) 10 + string requirement
String (fixed-length) String requirement

The above values however, don’t provide all the information you need to understand how much memory a particular array needs. More precisely:

When calculating how many bytes an array uses, you must generally consider the following 2 factors:

  • Factor #1: The data type of the array.
  • Factor #2: The number of elements in the array.

You can get an idea of the array size is determined by multiplying (i) the amount of bytes required by the relevant data type and (ii) the number of array elements. In mathematical terms:

Bytes used by array = (# of elements in array) x (bytes required by each element of array data type)

According to the Microsoft Dev Center (in the webpage I link to above), the maximum size of a VBA array depends on 2 main factors:

  • Your operating system.
  • Available memory.

As a general rule, execution is slower whenever you use an array whose size exceeds the RAM memory that’s available in the system you’re working with. This is because, as explained by Microsoft, “the data must be read from and written to disk”.

Now that you have a basic understanding of the relationship between array size, data types and memory requirements, let’s move on to the topic of…

One-Dimensional And Multidimensional VBA Arrays

The Dim keyword is short for “Dimension”. As I quote in the post about declaring VBA variables, the only use of Dim in older BASIC versions was to declare the dimensions of an array.

VBA arrays can have up to 60 dimensions. However, in practice you’ll usually work with (maximum) 2 or 3 dimensional arrays.

In order to understand what a dimension is, let’s take a look at the simplest case: a one-dimensional array. One-dimensional arrays can be visualized as a single line of items. The following image shows an illustration of an 8-element one-dimensional array.

One-dimensional VBA array visualization

If you add an additional dimension, you have a two-dimensional array. You can think of such an array as a grid where the elements are arranged in rows and columns. The following image illustrates a two-dimensional array with 16 elements organized in 4 rows and 4 columns.

Two-dimensional VBA array visualization

Notice how, in this particular case, I refer to each array element by using 2 numbers. The first number makes reference to the location within the first dimension (in this image the row) row where the element is located. The second number refers to the location in the second dimension (in this case, the column). I explain the topic of how to refer to array elements below.

If, once more, you add an additional dimension, you get a three-dimensional array. You can picture this array as a cube.

Three-dimensional VBA array visualization

I can’t provide an image to illustrate arrays of 4 or more dimensions. In any case, the purpose of the previous image is just to provide you a visual idea of what an array is.

Within the Visual Basic Editor, an array looks different. In the following sections, I provide several examples of statements that declare both one-dimensional and multidimensional arrays.

Fixed And Dynamic VBA Arrays

As I mention above, the basic difference you must be aware of when declaring an array (vs. a scalar variable) is that you usually specify the size of the array.

There are, however, 2 ways in which you can go about determining an array size:

  • Option #1: You can specify the size of the array. This results in a fixed-size array (fixed array).
  • Option #2: You can allow the size of the array to change as the relevant application runs. The result of this option is a dynamic array.

The usage of dynamic arrays is substantially the same as that of fixed arrays. The main difference between them is that fixed arrays are “un-resizable”.

As I explain above, the basic structure of the statement you can use to declare an array is as follows:

Declaring_Keyword Array_Name([Array_Size]) As [Data_Type]

I explain items #1 (Declaring_Keyword), #2 (Array_Name) and #4 (Data_Type) above.

I cover item #3 (Array_Size) in the following sections. Let’s start by taking a look at…

How To Declare A Fixed One-Dimensional Excel VBA Array

As a general rule, you set the size of an array dimension (Array_Size in the array declaration statement above) through the following 3 items:

  • Item #1: The first index number.
  • Item #2: The keyword “To”.
  • Item #3: The last index number.

In other words, the structure of the statement you use to declare an array can be rewritten as:

Declaring_Keyword Array_Name(First_Index_# To Last_Index_#) [As Data_Type]

This is perhaps the most basic array declaration you can make.

All the array declaration statements that I include as examples in this VBA tutorial use the Dim statement. Remember that, as I explain above, you can (theoretically) also use Private, Public or Static. The comments I make throughout this blog post generally apply to the cases where you’re working with those other statements as well.

Let’s take a look at 2 examples:

  • Example #1: The following statement declares an array of 10 integers (elements 0 to 9):

    Dim myArray(0 To 9) As Integer

  • Example #2: This statement declares an array of 20 strings (elements 0 to 19):

    Dim myArray(0 To 19) As String

Strictly speaking, you can set the size of an array by only specifying the upper index number. In other words, you can declare an array by omitting:

  • Item #1: The first index number.
  • Item #2: The keyword “To”.

Let’s take a look at how the 2 statement examples above look like if I declare them without a lower index:

  • Example #1: 10-integer array.

    Dim myArray(9) As Integer

  • Example #2: Array composed of 20 strings.

    Dim myArray(19) As String

In such cases, Visual Basic for Applications assumes that the lower index number is 0 (by default) or 1 (if you use the Option Base 1 statement). I explain this topic below. For the moment, note the following 2 points:

  • #1: The arrays declared by the statement samples above have 0 as lower index.
  • #2: This way of declaring an array doesn’t specify the number of array elements. It rather specifies the upper array bound.

As you start working with arrays, in any case, you may start realizing that including both an upper and a lower bound when declaring an array provides more flexibility than relying on the Option Base statement. Additionally, in certain cases, omitting the lower array bound may lead to bugs.

Due to, among others, these reasons, I personally prefer specifying both the upper and lower bound of an array over allowing the Option Base statement to determine the lower array boundary. VBA experts such as Chip Pearson (who I quote above) probably agree with this opinion. Chip’s opinion, which you can find by following the link above, is that it’s a…

Very poor programming practice to omit the lower bound and declare only the upper bound.

How To Declare A Fixed Multidimensional Excel VBA Array

The statement for declaring a fixed multidimensional array is very same to the statements that we’ve seen above to declare a one-dimensional array.

In practice, the main difference between declaring a one-dimensional and a multidimensional array is that, when declaring a multidimensional array, you separate the size of the dimensions with commas (,).

Therefore, the structure of the statement you use to declare an array with ## dimensions can be rewritten as:

Declaring_Keyword Array_Name(Dimension1_First_Index_# To Dimension1_Last_Index_#, Dimension2_First_Index_# To Dimension2_Last_Index_#, … , Dimension##_First_Index_# To Dimension##_Last_Index_#) [As Data_Type]

Let’s take a look at some examples of fixed multidimensional array declarations:

  • Example #1: The following statement declares a two-dimensional array with 25 integers. As I explain above, you can think of this array as a 5 x 5 grid.

    Dim myArray(1 To 5, 1 To 5) As Integer

    Visualization of two-dimensional array

  • Example #2: This statement declares a three-dimensional array with 1,000 integers. Following the logic behind the illustrations above, you can picture this as a 10 x 10 x 10 cube.

    Dim myArray(1 To 10, 1 To 10, 1 To 10) As Integer

    Visualization of three-dimensional array

  • Example #3: The following statement declares a four-dimensional array with 10,000 integers:

    Dim myArray(1 To 10, 1 To 10, 1 To 10, 1 To 10) As Integer

How To Declare And ReDim A Dynamic Excel VBA Array

As I explain above, the size of dynamic arrays changes as the relevant application runs. In other words (as explained in Excel VBA Programming for Dummies):

A dynamic array doesn’t have a preset number of elements.

The following are 2 of the main reasons to use dynamic arrays are:

  • Reason #1: You don’t know what is the required array size prior to execution.
  • Reason #2: You want to optimize memory usage by, for example, allocating very large arrays for only short periods of time.

When declaring a dynamic array, you don’t include a number of elements (Array_Size within the basic syntax above) in the declaration statement. This means that you leave the relevant set of parentheses empty.

The basic syntax of a statement declaring a dynamic array is, therefore, as follows:

Declaring_Keyword Array_Name() [As Data_Type]

The following sample statements declare dynamic arrays:

Dim myArray() As Integer

Dim myArray() As String

You can’t, however, use a dynamic array until you have specified how many elements the dynamic array has. To do this, you use the ReDim statement.

Let’s take a closer look at this topic:

ReDim Dynamic Array

The main purpose of the ReDim statement is to allow you to “reallocate storage space” for dynamic arrays. As I mention above, you use the ReDim statement to specify the number of elements that a dynamic array has.

You can’t use the ReDim statement to resize a fixed array. As explained at the Microsoft Dev Center, whenever…

You try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, or Dim statement, an error occurs.

The basic syntax of the ReDim statement is, to a certain extent, similar to that you use when declaring an array (which I explain above). More precisely, the basic structure is as follows:

ReDim [Preserve] Array_Name(Array_Size) [As Data_Type]

Items within square brackets ([ ]) are optional.

This statement contains the following 5 items:

  • Item #1: ReDim keyword.

    I explain the purpose of this keyword in the current section.

  • Item #2: Preserve keyword.

    This item is optional. I explain its purpose and characteristics further below.

  • Item #3: Array_Name.

    This is the name of the array you’re working with. I explain this element in the section above that covers the topic of declaring VBA arrays.

  • Item #4: Array_Size.

    This is the size of the array. This particular element is the one you’re usually specifying when working with the ReDim statement.

    I explain how you deal with this item starting in this section.

  • Item #5: As Data_Type.

    I introduce this particular item when explaining how to declare an array in a previous section. The comments I provide there generally apply to the cases where you’re using the ReDim Statement.

    Despite the above, there are a couple of particular rules that apply when you’re working with the ReDim statement. I explain these below.

As a general rule, you can use the ReDim statement as many times as you require in order to change the size of your dynamic arrays.

Despite the above, you can’t always redimension an array. More precisely, whenever you pass a VBA array to a procedure by reference, you can’t redimension that array within that procedure.

Let’s take a look at some particularities of the ReDim statement, before moving on to a code example:

The ReDim Statement And Data Types

As a general rule, you can’t use the ReDim statement to change an array data type that you’ve declared previously.

The basic exception to this rule are the cases where the array is contained in a Variant variable. In such cases, you can usually use item #5 above (As Data_Type] to change the data type.

Even in the cases where the array is contained in a Variant variable, you won’t be able change the array data type if your ReDim statement uses the Preserve keyword. This is because, when you’re using “Preserve”, data type changes are not allowed.

Independent of the above, note that in order to be able to resize an array contained in a Variant variable, you must declare the variable explicitly. The declaration statement must be before the statement that resized the array.

Now, let’s go back to…

The Preserve Keyword

As explained in Excel 2016 VBA and Macros, the ReDim statement “reinitializes” the array you’re working with. Therefore, as a general rule, ReDim erases any previously stored data within an array’s elements. In other words, that old data is destroyed.

You can, however, avoid destroying all of the previously existing data by using the optional Preserve keyword within the ReDim statement. As implied by its name, you can use the Preserve keyword to preserve data within an array.

Using the Preserve keyword comes with some conditions attached. The following are the most relevant conditions you should be aware about:

  • Condition #1: As explained in the previous section, data type changes aren’t generally allowed.
  • Condition #2: You can’t change the number of dimensions of the array.
  • Condition #3: You can only resize the last dimension of the array.
  • Condition #4: You can only change the upper array bound.

    Seen from the opposite perspective, you can’t change the lower bound of the array. If you try to do this, an error is caused.

Further to the above (although not strictly a condition), you may want to consider the fact that (as explained in Excel 2016 VBA and Macros), the Preserve keyword can slow down your VBA applications. This is the case, for example, when you have a large amount of data within a loop.

I provide some examples of ReDim statements that use the Preserve keyword below.

Reducing The Size Of A Dynamic Array

As a general rule, you can use the ReDim statement to reduce the size of a dynamic array.

In such cases, the data stored within the deleted elements is wiped out. This is the case even if you’re using the Preserve keyword.

ReDim Statement To Declare Variables

From a theoretical point of view, the ReDim statement can be used to declare variables. This is the case if ReDim makes reference to a variable that doesn’t exist at the module or procedure level.

Further to the above, as explained by Microsoft:

If another variable with the same name is created later, even in a wider scope, ReDim will refer to the later variable and won’t necessarily cause a compilation error, even if Option Explicit is in effect.

Due to the problems/conflicts that may arise as a consequence of the above, it’s advisable to avoid using the ReDim statement to declare variables. In other words, limit the use of the ReDim statement to the situations where you’re redimensioning an array.

ReDim Statement Code Example

As explained by Excel authority John Walkenbach in Excel VBA Programming for Dummies, whenever you’re working with a dynamic array, it’s usual that…

The number of elements in the array is determined while your code is running.

Therefore, for purposes of the example below, let’s assume the following 2 things:

  • Assumption #1: You’re working in a particular procedure that includes a variable named “dimensionSize”.
  • Assumption #2: The dimensionSize variable contains a certain value.

If that’s the case, the following sample statement uses the ReDim statement to change the size of the array:

ReDim myArray (1 to dimensionSize)

When working with a multidimensional array, you separate the size of the different dimensions with a comma (,). The logic is basically the same that I explain above for declaring a multidimensional array.

The following 3 statements are examples of how to use the ReDim statement when working with multidimensional arrays:

  • Example #1: If you have 2 variables containing values (dimensionSize1 and dimensionSize 2):

    ReDim myArray (1 to dimensionSize1, 1 to dimensionSize2)

  • Example #2: If you have 3 variables called “dimensionSize1” through “dimensionSize3”:

    ReDim myArray (1 to dimensionSize1, 1 to dimensionSize2, 1 to dimensionSize3)

  • Example #3: If you have 4 variables (dimensionSize1 through dimensionSize4):

    ReDim myArray (1 to dimensionSize1, 1 to dimensionSize2, 1 to dimensionSize3, 1 to dimensionSize4)

Finally, the following statements are samples of how you can use the Preserve keyword within the ReDim statement to preserve data within the relevant array. I introduce the Preserve keyword above.

  • Example #1: This example assumes that (i) the array (myArray) has 5 elements, and (ii) the dimensionSize variable has a value of 12. If that’s the case, the following statement preserves the data stored within the first 5 elements, and adds 7 new elements to the array (6 to 12):

    ReDim Preserve myArray (1 to dimensionSize)

  • Example #2: This example assumes that (i) myArray has 2 dimensions and 9 elements (3 x 3), and (ii) the dimensionSize variable has a value of 5. If this is the case, the following statement preserves the data stored within the array, and adds 6 new elements. The array size after this statement is 3 x 5.

    ReDim Preserve myArray (1 to 3, 1 to dimensionSize)

  • Example #3: This example assumes that (i) myArray has 3 dimensions and 8 elements (2 x 2 x 2), and (ii) dimensionSize’s value is equal to 5. In such a case, the following statements preserves the data stored in myArray and adds 12 elements. The resulting array size is 2 x 2 x 5.

    ReDim Preserve myArray (1 to 2, 1 to 2, 1 to dimensionSize)

When looking at these last 3 examples, remember that (as I mention above) you can only resize the last dimension of an array when using the Preserve keyword.

In example #1, you only have 1 dimension. That dimension is also the last dimension. In examples #2 and #3 you have more than 1 dimension. Therefore, in those 2 cases, I only change the size of the last dimension.

Lower Array Bounds And The Option Base Statement

As I explain above, it’s not mandatory to express the lower bound of an array.

Doing so doesn’t mean that there’s no lower bound. As explained by Excel authorities Bill Jelen (Mr. Excel) and Tracy Syrstad in Excel 2016 VBA and Macros, when you do this you’re actually “allowing” the Option Base statement to determine the lower bound.

When you do this, there are 2 options for array indexing:

  • Option #1: The array is indexed from 0.
  • Option #2: The array is indexed from 1.

You can determine which of the above 2 options applies to a particular array by using the Option Base statement.

The default indexing option is Option Base 0. Therefore, if you don’t specify the base when declaring an array, it begins at 0. This is the most common standard in programming.

In order to implement option #2 and have the array be indexed from 1, you use the Option Base statement. To do this, enter the following statement at the top of the module you’re working in and before any procedures:

Option Base 1

The following image shows the top of a particular module that includes both the Option Explicit statement and the Option Base 1 statement within the General Declarations section before the first procedure (One_Dimensional_Array_Declaration_1):

Option Base statement example in VBA

The Option Base statement:

  • Can only appear once per module.
  • Must “precede array declarations that include dimensions”.
  • Only changes the lower bound of arrays within the particular module that contains the Option Base statement.

You can’t use the Option Base statement to change the lower bound of arrays created using the ParamArray keyword. You may work with the ParamArray keyword to, among others, create User-Defined Functions that take an unlimited (up to 255) number of arguments.

Let’s go back to the examples of array declaration statements that I provide in the previous sections about fixed one-dimensional and fixed multidimensional arrays. The following examples assume that the relevant statement is within a module that contains the “Option Base 1” statement, as I explain above.

  • Example #1: Both of the following statements declare an array of 10 integers (elements 1 to 10):

    Dim myArray(1 To 10) As Integer

    Dim myArray(10) As Integer

  • Example #2: These statements declare an array with 20 strings (elements 1 to 20):

    Dim myArray(1 To 20) As String

    Dim myArray(20) As String

  • Example #3: The following statements resize an array with a number of elements equal to the value held by the dimensionSize variable (elements 1 to dimensionSize):

    ReDim myArray (1 to dimensionSize)

    ReDim myArray (dimensionSize)

How To Refer To An Array Element

The previous sections of this Excel tutorial focus on what an array is and how you can declare different types of arrays. This section explains how you can refer to a particular element within an array.

As a general rule, in order to identify a particular element of an array, you use its index number(s) for each of the array dimensions. Therefore, the basic syntax of the statement you use varies depending on how many dimensions the relevant array has. The number of index number(s) you must include in the reference is equal to that number of dimensions.

The following sections start by explaining how you can refer to an element within a one-dimensional array (the most basic case). I later show how the syntax varies (slightly) when you’re referring to elements within multidimensional arrays.

How To Refer To An Element In A One-Dimensional Array

As explained in Excel 2016 Power Programming with VBA, you generally refer to an array element by using 2 items:

  • Item #1: The name of the array.
  • Item #2: A particular index or subscript number.

The basic structure of the statement you can use to refer to an element within a one-dimensional array is as follows:

Array_Name(Element_Index_Number)

Let’s take a look at some examples:

The sample macro displayed in the following image (One_Dimensional_Array_Declaration_1), does the following 3 things:

  1. Declares an array of 10 integers (1 to 10).

    This statement follows the rules to declare a VBA array that I explain above.

  2. Initializes each array element and assigns the values 1 through 10 to each of these elements.

    This particular VBA tutorial doesn’t focus on the topic of the different ways you can assign values to the elements of an array. Even though there are other ways to fill an array, the examples I use throughout this blog post individually assign a value to each array element.

    I may dive deeper into the topic of array filling in a future blog post. If you want to receive an email whenever I publish new content in Power Spreadsheets, make sure to register for our Newsletter now by entering your email address below:

  3. Uses the MsgBox VBA function to display a dialog box with the value of the first element of the array (myArray(1)).

Sample VBA code for one-dimensional array

Notice how all of the element references within items #2 and #3 use the basic statement structure that I introduce above:

VBA code to fill array and obtain value of element

The effect of executing this sample macro is that Excel displays the following dialog box. Notice that the value within the message of the dialog is equal to that assigned to the first element of the array in the Sub procedure above.

Excel dialog box displays array element value

Sample VBA code with reference to array element

The following section takes this a step further and shows you…

How To Refer To An Element In a Multidimensional Array

The logic to refer to an element within a multidimensional array, is similar. The main rules for making reference to such an element are the following:

  • Rule #1: Include the relevant index number for each dimension of the array.
  • Rule #2: Separate the different index numbers with commas (,).

As a consequence of these rules, the basic structure of a reference to an element within an array with ## dimensions is as follows:

Array_Name(Dimension1_Element_Index_Number, Dimension2_Element_Index_Number, …, Dimension##_Element_Index_Number)

The following sample macro (Two_Dimensional_Array_Declaration) does the same 3 things as the Sub procedure example in the previous section. More precisely, it:

  1. Declares an array of 9 integers (3 x 3).

    I explain the syntax of this statement in a previous section of this tutorial.

  2. Initializes each array element and assigns values 1 through 9 to them.
  3. Displays a dialog box with the value of the first array element (1, 1).

Sample VBA code with two-dimensional array

The following image shows the dialog box that Excel displays when I execute this macro:

Dialog box displaying array element value

Notice how, as expected, the displayed value matches with that assigned to the first array element within the VBA code:

VBA code example with element referencing

Let’s take a look at a final example macro (Three_Dimensional_Array_Declaration), where the macro works with a three-dimensional array. This sample macro does the following:

  1. Declares an array of 8 integers (2 x 2 x 2).
  2. Initializes each array element and assigns values 1 through 8 to each element.
  3. Displays a message box with the value assigned to the first array element (1, 1, 1).

Sample VBA code with three-dimensional array

The dialog box that Excel displays when I execute the macro is (as expected) substantially the same as that in the previous examples:

Excel dialog box displaying value of array element

Notice how, once again, the value displayed by Excel matches that assigned to the first array element by the VBA code:

VBA code example with initialization of three-dimensional array

How To Erase The Data In An Array (Or The Array Itself)

As I explain above the ReDim statement generally wipes out the data within the array you’re working with.

You can, however, erase the data stored within an array with a different statement: Erase.

The main purpose of the Erase statement is to:

  • Reinitialize the elements of a fixed array.

    The Erase statement doesn’t recover memory when working with a fixed array. It generally sets the array elements to the default values of the relevant data type.

  • Release “dynamic-array storage space”.

    In the case of dynamic arrays, therefore, the Erase statement frees the memory that the array was using. This, basically, erases the dynamic array completely. Therefore, before you’re able to use the array in the future, you must specify how many elements it has by using the ReDim statement. I explain how to do this above.

The basic syntax of the Erase statement is quite straightforward:

Erase arraylist

For these purposes, arraylist is the list of array(s) to be erased. If you’re erasing more than 1 array, separate them with a comma (,).

The following sample statements show how you can use the Erase statement:

  • Example #1: This statement erases the data stored within myArray (if it’s fixed) or myArray itself (if it’s dynamic):

    Erase myArray

  • Example #2: The following statement erases the data stored within both myArray1 and myArray2 (if they’re fixed) or the arrays themselves (if they’re dynamic):

    Erase myArray1, myArray2

Conclusion

After reading this VBA tutorial, you probably have a very solid understanding of the topic of Excel VBA arrays. Among other things, you know:

  • What are VBA arrays, and why they’re useful.
  • What are one-dimensional and multidimensional VBA arrays. This includes their commonalities and differences.
  • What are fixed and dynamic arrays, how they’re similar and how they differ.
  • The relationship between array size, data types and memory requirements, and why this relationship is important.
  • How can you declare an array depending on whether it’s fixed (one-dimensional or multidimensional) or dynamic.
  • How are lower array bounds determined if you don’t explicitly specify them, and what is the Option Base statement.
  • How to use the Erase statement when working with arrays.

This Excel VBA Array Tutorial is accompanied by an Excel workbook containing the data and macros I use in the examples above. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Books Referenced In This Excel Tutorial

  • Alexander, Michael and Kusleika, Dick (2016). Excel 2016 Power Programming with VBA. Indianapolis, IN: John Wiley & Sons Inc.
  • Jelen, Bill and Syrstad, Tracy (2015). Excel 2016 VBA and Macros. United States of America: Pearson Education, Inc.
  • Mansfield, Richard (2016). Mastering VBA for Microsoft Office 2016. Indianapolis, IN: John Wiley & Sons Inc.
  • Walkenbach, John (2015). Excel VBA Programming for Dummies. Hoboken, NJ: John Wiley & Sons Inc.

Понравилась статья? Поделить с друзьями:
  • Array vba excel описание
  • Array to excel phpexcel
  • Array of arrays in excel vba
  • Array indexing in excel vba
  • Array in excel with example