Excel VBA Multidimensional Array for Assigning Values (6 Ways)

How to Launch the VBA Editor in Excel

  • Go to the Developer tab and select Visual Basic under Code.

Activate Visual Basic Editor window with Developer tab in Excel

Alternative command: Pressing Alt + F11 will also take you to the VBA window.

There are 3 ways to insert code in the Visual Basic Editor window.


Method 1 – Using the Module Window

  • Click the Insert tab of the VBA window and select Module.

Insert Module in the Excel VBA window

  • You will see a Module window has popped up right beside the Project – VBAProject. Insert the code you want to execute in this window.

Module window for inserting VBA code in Excel

You can either use multiple Modules for different Macros or insert your Macros one after another in the same Module. If you have different macros for serving different purposes, then it is preferable to use different Modules as it will help find your macros quickly.

Note: The code in the Module can be used for any worksheet of the workbook.

Method 2 – Utilizing the Sheet Code Window

  • After opening the Visual Basic Editor, right-click on the sheet name.

Right-click on the sheet name to activate code window

  • From the menu, select View Code.

Select the View Code option from the menu

  • You will see the Sheet (Code) window on the screen.

Sheet (Code) window for inserting VBA code

Note: The code inserted in the sheet code window only works for that specific sheet.


Method 3 – Adding a Button for the Macro

By adding a button and assigning Macro to that button, you can faster and automate your task.


Introduction to Arrays in Excel VBA


Arrays Based on Dimension

Case 1 – One-Dimensional Array

One-dimensional array data

A one-dimensional array is a collection of related data values stored in a single row or column of cells. It is essentially a list of values that can be accessed using a single variable name. To create a one-dimensional array in Excel VBA, you can declare it using the Dim statement, specifying the data type of the elements and the number of elements in the array.

One dimensional array example

Code:

Sub OneDimensionalArray()
Dim Arr(1 To 3) As String
Arr(1) = 5
Arr(2) = 10
Arr(3) = 15
End Sub

Case 2 – Multi-Dimensional Array

Data for multidimensional array

A multidimensional array is a collection of related data values stored in multiple rows and columns of cells. It is essentially a table of values that can be accessed using multiple variable names.

Example of multidimensional array

Code:

Sub MultiDimensionalArray()
Dim Arr(1 To 3, 1 To 3) As String
Arr(1, 1) = 5
Arr(2, 1) = 10
Arr(3, 1) = 15
Arr(1, 2) = 6
Arr(2, 2) = 12
Arr(3, 2) = 18
End Sub

Based on Size

Case 1 – Static Array

The default array size starts from 0. If an array with size 2 means that it can store 3 values at a time. A Static array has a fixed number of elements and a fixed size, which is determined at the time of declaration. Once the size of the array is set, it cannot be changed.

Static array example

The image above describes that the array has a size of 3 which means it can’t store values of more than 3.

Code:

Sub StaticArray()
Dim Arr(2) As Integer
End Sub

Case 2 – Dynamic Array

A dynamic array is an array that can be resized during runtime. In contrast to a static array, where the size is determined at compile time, a dynamic array can be resized based on the current needs of the program.

To create a dynamic array in VBA, you first declare the array without specifying a size.

Dynamic array with ReDim statement

After that, declare the array size with the ReDim statement.

Code:

Sub DynamicArray()
Dim Arr() As Integer
ReDim Arr(2)
End Sub

How to Declare a Multidimensional Array in Excel VBA

In Excel VBA, the array is declared with the Dim command at the beginning of the subprocedure. For a multidimensional array, you have to use commas to separate each dimension.

Declare a multidimensional array

Code:

Sub DeclaringArray()
Dim SalesData(1 To 5, 1 To 2) As Variant
End Sub

This creates an array called SalesData with 5 rows and 2 columns, where each element of the array is a variant (integer or string).

Read More: Excel VBA to Declare Multidimensional Array of Unknown Size


Excel VBA Multidimensional Array for Assigning Values: 6 Suitable Examples


Example 1 – Populating an Excel Sheet by Assigning Values Directly Inside Code

VBA multidimensional array for assigning values directly from code

You can just directly assign values to your array with the relevant dimension index and use this array to populate your Excel sheet with the array values. Here’s a sample example of populating a worksheet with array values assigned in code directly.

Assign values to multidimensional array directly in VBA code

Code:

Sub PopulateWorksheet()
Dim ArrVal(4 To 7, 2 To 4) As Integer
Dim i As Integer
Dim j As Integer
ArrVal(4, 2) = 45
ArrVal(4, 3) = 50
ArrVal(4, 4) = 55
ArrVal(5, 2) = 60
ArrVal(5, 3) = 65
ArrVal(5, 4) = 70
ArrVal(6, 2) = 75
ArrVal(6, 3) = 80
ArrVal(6, 4) = 83
ArrVal(7, 2) = 86
ArrVal(7, 3) = 90
ArrVal(7, 4) = 93
For i = 4 To 7
For j = 2 To 4
Cells(i, j).Value = ArrVal(i, j)
Next j
Next i
End Sub

Read More: Excel VBA to Populate Array with Cell Values


Example 2 – Assigning Values to Array from One Sheet to Another

Assign values to an array from one sheet to populate another

When you don’t want to assign values to your array within code directly, rather you need to assign values to the array from worksheet data, in that case, this method is useful. The VBA code used here will hold the array values by reading data from one worksheet and then populating another one.

VBA code for assigning values to array from one worksheet

Code:

Sub PopulatingAnotherSheet()
'Define the source worksheet and range
Dim srcWS As Worksheet
Set srcWS = ThisWorkbook.Worksheets("Directly")
Dim srcRange As Range
Set srcRange = srcWS.Range("B4:F8")
'Define the destination worksheet and range
Dim destWS As Worksheet
Set destWS = ThisWorkbook.Worksheets("Another Sheet")
Dim destRange As Range
Set destRange = destWS.Range("B4:F8")
'Copy the data to an arra
Dim dataArr() As Variant
dataArr = srcRange.Value
'Copy the array to the destination range
destRange.Value = dataArr
End Sub

Code Breakdown

The code copies data to the array from the source range (“B4:F8”) of the source worksheet “Directly” to the destination range (“B4:F8”) of the destination worksheet “Another Sheet”.


Method 3 – Applying “For” Loops to Assign and Display Multidimensional Array Values


Case 3.1 – Using the Range Object for Assigning Values to an Array

The Range object in Excel VBA represents a cell or a range of cells in a worksheet. A range can be a single cell, a row, a column, or a rectangular block of cells.

Use of Range object in VBA for assigning values to array

Here’s an example of a multidimensional array using the “For” loop with the “Range” object. An array will be created by multiplying the current Row and Column index number with the loop.

VBA code with application of Range object with For loop

Code:

Sub MultiDimensionalArrayExample()
Dim myArray(4 To 6, 2 To 5) As Integer
For i = 4 To 6
For j = 2 To 5
myArray(i, j) = i * j
Range("B" & i & ":E" & i).Cells(j - 1) = myArray(i, j)
Next j
Next i
End Sub

Code Breakdown

The code writes the values of the myArray to a range of cells in the worksheet. The Range object is used to specify the range of cells B4:E6 where the values should be written. The Cells property is then used to select the appropriate cell within the range, based on the current value of i and j.

The code will show the result below after executing.


Case 3.2 – Utilizing UBound and LBound Functions

In Excel VBA, UBound stands for “Upper Bound” and returns the highest available index number and LBound stands for “Lower Bound” and returns the lowest available index number for a specified array dimension.

The code below utilizes VBA UBound and LBound functions and returns the same result gained with Method 3.1.

Use of UBound and LBound functions in VBA for assigning values to array

Code:

Sub MultiDimensionalArrayExample2()
Dim myArray(4 To 6, 2 To 5) As Integer
Dim i As Long, j As Long
' Fill the array with values
For i = LBound(myArray, 1) To UBound(myArray, 1)
For j = LBound(myArray, 2) To UBound(myArray, 2)
myArray(i, j) = i * j
Next j
Next i
' Print the array values in the range "B4:E6"
For i = LBound(myArray, 1) To UBound(myArray, 1)
For j = LBound(myArray, 2) To UBound(myArray, 2)
Range("B" & i & ":E" & i).Cells(j - 1) = myArray(i, j)
Next j
Next i
End Sub

The code first fills the array values with the predefined size using the UBound and LBound functions and prints the array values in the range “B4:E6”. In this way, we can have VBA multidimensional array for assigning values.

Read More: How to Use UBound on Multidimensional Array with VBA in Excel


Example 4 – Assigning New Values to a 2D Dynamic Array with “ReDim” Statement

Cake 10
Fruit 5
Drinks 20

Consider the scenario above where we have values that we can utilize for a 2 Dimensional array. Inserting the array name with a blank parenthesis is used to make the array size dynamic. Applying the ReDim statement afterward fixes the size. The ReDim statement is used to change the size of an existing dynamic array at runtime. But applying the ReDim statement changes the size of an existing array and assigns new values to the array.

Consider the following example where a dynamic array is declared with Dim Arr() syntax and the size of the array is declared 3×2 with the ReDim Arr(0 To 2, 0 To 1) statement.

ReDim statement for assigning new values to array in VBA

Code:

Sub ResizingArray()
Dim Arr() As String
ReDim Arr(0 To 2, 0 To 1)
Arr(0, 0) = "Cake"
Arr(0, 1) = "10"
Arr(1, 0) = "Fruit"
Arr(1, 1) = "5"
Arr(2, 0) = "Drinks"
Arr(2, 1) = "20"
MsgBox Arr(1, 0)
End Sub

In this code, the array size is not declared first with the Dim Arr() statement. Next the ReDim Arr(0 To 2, 0 To 1) statement is applied to define a 3×2 array, and the values are assigned to the array. You can show a random array value with MsgBox to check whether the new values are really encountered or not.

The ReDim statement clears the previous array and assigns a new array. If the ReDim statement is encountered again, it will clear the previous array value and create a new array. If no values are assigned again, the array will hold nothing.

Resize array with ReDim statement in VBA

Code:

Sub ResizingArray()
Dim Arr() As String
ReDim Arr(0 To 2, 0 To 1)
Arr(0, 0) = "Cake"
Arr(0, 1) = "10"
Arr(1, 0) = "Fruit"
Arr(1, 1) = "5"
Arr(2, 0) = "Drinks"
Arr(2, 1) = "20"
'Reset the array size
ReDim Arr(0 To 3, 0 To 1)
MsgBox Arr(1, 0)
End Sub

This time the second ReDim will clear the value assigned with the first ReDim.

Read More: How to Redim 2D Array with VBA in Excel


Example 5 – Preserving Previous Data with a 2D Dynamic Array Using the “ReDim Preserve” Statement

Preserve previously assigned array value

The ReDim statement clears the previous array values keeping the memory blank. But sometimes you may need to increase the array size but keep the previous array values in memory. If you use the ReDim statement again, it will redefine the size as well as potentially clear array values. In that case, the ReDim Preserve statement is a lifesaver. It not only resizes the array but also keeps the previous value at the same time.

Resize the array to add another row with storing the previous value

Code:

Sub PreservingValue()
Dim Arr() As String
ReDim Arr(0 To 2, 0 To 1)
Arr(0, 0) = "Cake"
Arr(0, 1) = "10"
Arr(1, 0) = "Fruit"
Arr(1, 1) = "5"
Arr(2, 0) = "Drinks"
Arr(2, 1) = "20"
'Resize the array to add another row
ReDim Preserve Arr(0 To 2, 0 To 2)
MsgBox Arr(1, 0)
End Sub

One thing that should be kept in mind is that you can only resize the second dimension of the 2D array with ReDim Preserve. If you try to change the first dimension, it will show you a Run time error.

Unavailability of resizing first dimension of multidimensional array

If you had a 1-dimensional array with 10 elements, you could use Preserve to keep the first 5 elements and add 5 more elements to the end of the array. However, you have seen that this functionality is not available for multi-dimensional arrays.

To resize a multi-dimensional array while preserving the existing data, you’ll need to create a new array and copy the values from the old array to the new array. Here’s an example of how you can do this.

Resizing first dimension of a multidimensional array

Code:

Sub ResizeMultiDimArray()
Dim Arr() As String
Dim NewArr() As String
Dim i As Long, j As Long
ReDim Arr(0 To 2, 0 To 1)
Arr(0, 0) = "Cake"
Arr(0, 1) = "10"
Arr(1, 0) = "Fruit"
Arr(1, 1) = "5"
Arr(2, 0) = "Drinks"
Arr(2, 1) = "20"
'Resize the array to add another row
ReDim NewArr(0 To 3, 0 To 1)
For i = 0 To UBound(Arr, 1)
For j = 0 To UBound(Arr, 2)
NewArr(i, j) = Arr(i, j)
Next j
Next i
NewArr(3, 0) = "Snacks"
NewArr(3, 1) = "15"
MsgBox NewArr(3, 1)
End Sub

This will resize the first dimension and show the value in the message box.

Read More: How to ReDim Preserve 2D Array in Excel VBA


Example 6 – Assigning New Values to a 3D Array

A 3D array in Excel VBA is a data structure that consists of three dimensions. By using a 3D array in Excel VBA, you can efficiently store and manipulate large amounts of data in a three-dimensional format.
In VBA, when you declare an array with fixed dimensions that cannot be changed afterward. However, you can modify the values of the individual elements within the array without changing the array’s size using the index number of the array element.
The code below demonstrates how to work with 3-dimensional arrays in Excel VBA and how to assign new values to specific elements of the array.

Assign new values to 3Dimensional array

Code:

Sub AssignNewValuesTo3DArray()
Dim Arr(0 To 2, 0 To 2, 0 To 2) As Integer
Arr(0, 0, 0) = 1
Arr(0, 0, 1) = 2
Arr(0, 0, 2) = 3
Arr(0, 1, 0) = 4
Arr(0, 1, 1) = 5
Arr(0, 1, 2) = 6
Arr(0, 2, 0) = 7
Arr(0, 2, 1) = 8
Arr(0, 2, 2) = 9
Arr(1, 0, 0) = 10
Arr(1, 0, 1) = 11
Arr(1, 0, 2) = 12
Arr(1, 1, 0) = 13
Arr(1, 1, 1) = 14
Arr(1, 1, 2) = 15
Arr(1, 2, 0) = 16
Arr(1, 2, 1) = 17
Arr(1, 2, 2) = 18
Arr(2, 0, 0) = 19
Arr(2, 0, 1) = 20
Arr(2, 0, 2) = 21
Arr(2, 1, 0) = 22
Arr(2, 1, 1) = 23
Arr(2, 1, 2) = 24
Arr(2, 2, 0) = 25
Arr(2, 2, 1) = 26
Arr(2, 2, 2) = 27
' Assign new values to the array
Arr(0, 0, 0) = 100
Arr(1, 1, 1) = 200
Arr(2, 2, 2) = 300
MsgBox Arr(1, 1, 1)
End Sub

After initializing the array, the code assigns new values to three specific elements of the array. The element at position (0,0,0) is assigned a value of 100, the element at position (1,1,1) is assigned a value of 200, and the element at position (2,2,2) is assigned a value of 300.

The code displays a message box showing the value of the element at position (1,1,1), which should be 200.

Read More: Excel VBA 2 Dimensional Array Initialization


How to Use a Multidimensional Array in Excel VBA

Here’s a simple dataset of product sales across regions and quarters.

Dataset for showing use of Array

We will find sales for a specific product, Region and quarter (Q1/Q2/Q3/Q4).

VBA code to get specific array value from dataset

Code:

Sub GetSalesData()
Dim SalesData() As Variant
Dim Product As String
Dim Region As String
Dim Quarter As String
Dim i As Long, j As Long, k As Long
Dim Found As Boolean
SalesData = Range("B5:G14").Value ' Update range based on your dataset
' Get input values from user
Product = InputBox("Enter Product:")
Region = InputBox("Enter Region:")
Quarter = InputBox("Enter Quarter (Q1/Q2/Q3/Q4):")
' Loop through sales data to find matching values
For i = LBound(SalesData, 1) To UBound(SalesData, 1)
If SalesData(i, 1) = Product And SalesData(i, 2) = Region Then
Found = True
Select Case Quarter
Case "Q1"
MsgBox "Q1 Sales: " & SalesData(i, 3)
Case "Q2"
MsgBox "Q2 Sales: " & SalesData(i, 4)
Case "Q3"
MsgBox "Q3 Sales: " & SalesData(i, 5)
Case "Q4"
MsgBox "Q4 Sales: " & SalesData(i, 6)
Case Else
MsgBox "Invalid quarter entered."
End Select
Exit For
End If
Next i
If Not Found Then MsgBox "No matching data found."
End Sub

The code will take input in the input box and show output in message box.

Note: In the dataset, Product “B” is available in 2 regions: “East” and “West”. So, in the input box, we can insert a random “B” and then choose either “East” or “West”. You have no restrictions if you need to choose the region “East”, you have to select product “B” from the same row. You can choose any “Product” and select “Region” from a different row.

How to Reset Array Values to Default in Excel VBA

Resetting Array values with VBA

The VBA Erase function clears all the array values.

Code:

Sub ResetArray()
Dim MyArray(1 To 10) As Integer
Dim i As Integer
' Initialize array with some values
For i = 1 To 10
MyArray(i) = i
Next i
' Reset array to default values
Erase MyArray
' Verify that array is now empty
For i = 1 To 10
Debug.Print MyArray(i) ' This will print 0 for each element
Next i
End Sub

How to Get the Length of a Multidimensional Array in Excel VBA

Use the following code:

VBA code to get the array length

Code:

Sub ArrayLength()
' Prompt the user to select a range on the worksheet
Dim selectedRange As Range
Set selectedRange = Application.InputBox(prompt:="Select a range to convert to array", Type:=8)
' Convert the selected range to an array
Dim selectedArray() As Variant
selectedArray = selectedRange.Value
' Get the length of the first dimension of the array
Dim length As Integer
length = UBound(selectedArray, 1) - LBound(selectedArray, 1) + 1
' Output the length to the immediate window
MsgBox "Length of selected array: " & length
End Sub

Read More: VBA to Get Array Dimensions in Excel


How to Use an Array and Split Functions Together to Separate Values in Excel VBA

We have a single cell that contains an array of values.

Split string with Array and Split functions

When you have multiple strings in one cell and you want to split the string and put them in distinct cells, use the following VBA code.

VBA code to separate array values

Code:

Sub SplittingString()
Dim inputString As String
Dim outputArray() As String
Dim i As Integer
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Separate") ' Change "Sheet1" to your worksheet name
' Get the input string from cell B4
inputString = ws.Range("B4").Value
' Split the input string by comma
outputArray = Split(inputString, ",")
' Output the substrings into the range F4:F7
For i = 0 To UBound(outputArray)
ws.Cells(i + 4, 6).Value = Trim(outputArray(i))
Next i
End Sub

How to Sort a Multidimensional Array in Excel VBA

We have a 2D array based on product names and regions.

Take Array value from worksheet and sort the values

When you need to take an array from a worksheet and sort the array, this method is useful in that case.

VBA code to sort array value in worksheet

Code:

Sub SortSales()
' Declare variables
Dim arr() As Variant
Dim i As Integer, j As Integer
Dim temp As Variant
' Get the range of data
arr = Range("B5:D14").Value
' Sort the array based on "Sales"
For i = LBound(arr, 1) To UBound(arr, 1)
For j = i + 1 To UBound(arr, 1)
If arr(j, 3) < arr(i, 3) Then
temp = arr(i, 1)
arr(i, 1) = arr(j, 1)
arr(j, 1) = temp
temp = arr(i, 2)
arr(i, 2) = arr(j, 2)
arr(j, 2) = temp
temp = arr(i, 3)
arr(i, 3) = arr(j, 3)
arr(j, 3) = temp
End If
Next j
Next i
' Output the sorted array to the worksheet
Range("F5").Resize(UBound(arr, 1), UBound(arr, 2)).Value = arr
End Sub

Advantages of Using a Multidimensional Array

  • Multidimensional arrays allow you to organize data in a more structured and intuitive way.
  • Using multidimensional arrays in Excel VBA can improve performance by reducing the number of loops and iterations in your code.
  • Multidimensional arrays can simplify your code by allowing you to perform operations on multiple dimensions of data at once, rather than having to loop through multiple one-dimensional arrays.
  • Multidimensional arrays in Excel VBA are highly flexible and can be used in a wide variety of applications, including data analysis, financial modeling, and simulation.

Takeaways from This Article

  • To declare a multidimensional array in VBA, you need to specify the number of dimensions and the size of each dimension.
  • You can assign values to a multidimensional array in VBA using nested loops that iterate over each dimension of the array.
  • You can use the LBound and UBound functions to determine the lower and upper bounds of an array.
  • You can use the ReDim statement to resize a multidimensional array. When you resize an array, you can preserve the existing values by using the ReDim Preserve.

Things to Remember

  • The default array index in Excel VBA is 0 for all dimensions of the array. You can start the array index from 1 by declaring it.
  • The ReDim statement only changes the second dimension of the array. If you try to change the first dimension, the code will show you a Run time error after execution.

Frequently Asked Questions

How do you access an element of a multidimensional array?

To access an element of a multidimensional array, you need to specify the indices for each dimension of the array. For example, if you have a two-dimensional array named “myArray” with dimensions 1 to 3 and 1 to 2, you can access the element in the second row and first column using the myArray(2,1) syntax.

How data is stored in a multidimensional array?

In a multidimensional array, data is stored in a tabular format, where the first dimension represents the rows and the second dimension represents the columns.


Download the Practice Workbook

Get FREE Advanced Excel Exercises with Solutions!

Tags:

Rafiul Hasan
Rafiul Hasan

Rafiul Hasan, holding a BSc in Naval Architecture and Marine Engineering from Bangladesh University of Engineering & Technology, contributes significantly to the ExcelDemy project with almost 1.6 years of dedicated work. Currently an Excel and VBA Content Developer, he has a passion for problem-solving. Authoring over 100 articles for ExcelDemy showcases expertise in Microsoft Office Suites and Data Analysis. In addition to content development, Rafiul actively engages with the ExcelDemy forum, offering valuable solutions to user queries and... Read Full Bio

We will be happy to hear your thoughts

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo