Open In App

VBA Arrays in Excel

Last Updated: 16 Oct, 2022

A

Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Arrays are used to store data of similar data types. Suppose there are 300 students rather than declaring 300 variables for students, we can declare one array where we can store 300 elements. In this article, we will learn about excel VBA arrays. 

Declaration of Array 

Declaring an array is similar to declaring a variable in VBA. If we just mention, the size of a variable in parenthesis, then the variable becomes an array. For example, An array is declared with the name of arr, of 50. Here, the size of the array is 51, and the data type is the currency.

Syntax: Dim arr(size_of_array) as data_type

Note: In other programming languages, like C, C++, javascript, python etc. If an array of size n is created, then the indexes, range from [0, n-1], where 0 and n-1 are included, but in VBA by default, if an array of size n is created, then the indexes, range from [0, n], where 0 and n are included. Hence, VBA array of declaration n, is ultimately an array of size n+1. 

declaring array

 

Assigning Values to the Array

Assigning values means that an element is set to the value. For example, an array name arr of 50 is declared. Then a loop is passed on the array, and each element of the array is assigned the value 30

Syntax: arr(index) = value

assigning values to array

 

Changing Lower and Upper Bound

As, we discussed, above in a Note. That, arr(50), has an array size 51. So, what if we want to create an array of size 50, with 0-based or 1-based indexing? For example, if we want to change the lower bound from 0 to 1 then we can do it two ways: 

Note: By default, the lower bound of an array is 0, and the upper bound of an array is n. 

where, 

lower bound is the lowest index of the array, 

upper bound is the highest index of the array.  

Using “Option Base”

Option Base statement is written at the top of the module to change the default index from 0 to 1. 

Option base in vba array

 

Using the “To” clause

We can, Explicitly, can set the lower bound using the To clause. For example, arr(1 To 51), this array has a size of 50, with 1-based indexing. 

To clause in vba arrays

 

Storing values of Variant data types in Arrays

Variant data types are those where any kind of data type can be stored like string, integer, date, etc. There are two methods, to store values in variant data types in arrays: 

Method 1

The size of the array is predefined, i.e. 3. For example, an array of 2 is created. The value of arr[0] is a string, arr[1] is also a string, and arr[2] is a number

variant assigning in method 1

 

Method 2

The size of the array is not predefined, and the values are assigned, directly to the array. Use, Array() function to achieve this. For example, arr = Array(“Ayush”, “123 Ayush”, 123)

variant assigning in method 2

 

Using Multidimensional Arrays 

Declaration of a Multidimensional Array

We can declare a 2-dimensional array, by adding an additional size by comma separation. For example, if we want to create an array of 4 rows and 6 columns. Then the array declaration could be, Dim arr(1 To 4, 1 To 6) As Currency. 

Syntax: Dim arr(Rows, Columns) As data_type

declaring multidimensional array in vba

 

Assigning Values to a Multidimensional Array

We will use a nested For Next loop to assign the values in the multidimensional array. The below Picture illustrates the nested for loop, assigning of values in a multidimensional array. 

Syntax: arr(i, j) = value

where, 

i = index of the row,

j = index of the column, 

value = the value which has to be assigned. 

assigning value to multidimensional array

 

Functions in Arrays

There are ten-plus in-built functions in an array. These functions, help make our task more handy and easy. Here, we will discuss some of the most commonly used functions in arrays in VBA. 

Erase

The Erase function clears all the elements in the array. For example, we have declared an array of size 3, and assigned values to them. Now, we want to erase all the elements in the array, i.e. Erase arr

Syntax: Erase Array_name

where, 

Array_name = It is the name of the array, whose elements are to be deleted. 

erase function in vba array

 

ReDim

The ReDim() function is used to change the dimension of the array. For example, initially, we declared an array of size 3, now we want to reassign the value of dimension to 2 in the array. The ReDim arr(1 To 2) can be used to achieve this. 

Syntax: ReDim Array_name(row, column)

where,

Array_name = It is the name of the array, for which the dimension has to be changed,

row = number of rows to be reassigned,

columns = number of columns to be reassigned

ReDim function in vba array

 

Join

The Join() function is used to join the elements of arrays into one variable. For example, an array of size 3, is created, and the values, assigned, to them are 10, 20, and 30. Now, if we want to concatenate, all the elements. Then, Join(arr) function can be used. The final output of the program will be 102030

Syntax: Join(Array_name) 

where, 

Array_name: It is the name of the array. For example, arr in the below image. 

Join function in vba array

 

Split

The Split() function, is used to split the string into an array, using a delimiter as a separator. For example, we have a string month_12 = “april,may,june”, now, we want to convert this string into an array, where each element is the name of the month. We can use Split(month_12, “,”), to achieve, this task. The final array will be (april, may, june)

Syntax: Split(string, delimiter)

where, 

string = It is the string, from which the array has to be created, 

delimiter = It is the separation parameter, on which basis the string will break into the array. For the below example, “,”(comma) is the delimiter. 

split function in vba array

 



A

News
Improve
Discuss
Do you want to advertise with us?Click here to know more

VBA Subroutine in Excel - How to Call Sub in VBA?

article_img
When a specified action is performed on a worksheet with the help of a collection of code known as a VBA Subroutine. It also helps to read an external file, also it can open other applications from Excel. A large piece of code can be broken into small parts so that we can manage it easily. Let's learn why to use submarines: Converts large piece of codes into small parts so that the computer ignores all kind of complexities that arises because of large codesReusability of code suppose we in a program have to access the database frequently so instead of writing the code again and again we can create a function to access the databaseSubroutines are self-documenting functions which means a coder can easily say what the program does by looking into the name of the function Naming Rules of SubroutinesIt can start with a letter or an underscore but it cannot start with a number or a special character.It cannot contain any space in the name.The name of the subroutine cannot be a keyword like Private, Sub, End, etc. Syntax Private Sub function_name( ByVal arg1 As String, ByVal arg2 As String) End Sub Syntax Explanation Code Action "Private Sub function_name(...)"Private is the keyword whic
Read More

Multidimensional Arrays in Excel VBA

article_img
Multidimensional Arrays are used to store data of similar data types of more than one dimension. A multidimensional array has a dimension up to 60 but usually, we don't use arrays of dimensions more than 3 or 4. Here, we will see how to declare a multidimensional array in many ways and also how to create and re-size the multidimensional array Declare a 2D Array To declare a 2D array we have to use "Dim" then the name of the variable where it will store the 2D array and the dimension of the 2D array will be separated by commas. In the following code, a 2D array is declared as a "4 x 5" 2D array in a single line which is also known as a fixed array whose dimension can't be changed later This same array can also be declared explicitly using "To" Dynamic Array It is used to declare an array in two lines and we can also change the dimension of the array. Only the upper bound of the last dimension i.e column can be changed Note: By default, the lower bound of an array is 0, and the upper bound of an array is n. Where, Lower bound is the lowest index of the array.Upper bound is the highest index of the array. In the following code, an array variable is declared in one line using "Dim
Read More

How to Use Select Case Statement in Excel VBA?

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. In this article, we are going to discuss how to use Select Case Statement in Excel VBA. Select Case Statement of Excel VBA The select case in VBA is like a detective that investigates an expression by checking it against different scenarios listed as Case Statements, each with its own conditions. When a scenario matches the expression, it's like solving a piece of the puzzle, and the corresponding code linked to that scenario is activated. Importantly, once a match is found, the detective stops investigating and moves on to executing the discovered code. Yet, if none of the scenarios match, it's like the detective hitting a dead end. In this situation, the code associated with the Case Else statement comes into play, offering a default solution or outcome. Syntax of the Select Case Statement of Excel VBAThe VBA Select Case Statement shares similarities with the Switch Case construct found in programming languages such as Java, C#, and PHP. In Excel VBA, this statement helps
Read More

Excel VBA Concatenation Operators

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. Concatenation means to join two or more data into a single data. There are various ways we can perform concatenation in Excel using built-in functions, operators, etc. Some helpful links to get more insights about concatenate and using VBA in Excel : Record Macros in ExcelCONCATENATE in ExcelHow to Create a Macro in Excel? In this article, we are going to see about concatenate operators and how to use VBA to concatenate strings as well as numbers. Implementation : In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. The Developer Tab can be enabled easily by a two-step process : Right-click on any of the existing tabs at the top of the Excel window.Now select Customize the Ribbon from the pop-down menu.In the Excel Options Box, check the box Developer to enable it and click on OK. Now, the Developer Tab is visible. Now, we need to open the Visual Basic Editor. There are two ways : Go to Developer and directly click on the
Read More

Excel VBA Comparison Operators

article_img
VBA in Excel stands for Visual Basic for Applications which is Microsoft's programming language. To optimize the performance and reduce the time in Excel we need Macros and VBA is the tool used in the backend. Some helpful links to get more insights about Macros, VBA in Excel : 1. Record Macros in Excel. 2. How to Create a Macro in Excel? In this article, we are going to discuss various comparison operators in Excel VBA. Implementation : In the Microsoft Excel tabs, select the Developer Tab. Initially, the Developer Tab may not be available. The Developer Tab can be enabled easily by a two-step process : Right-click on any of the existing tabs in the top of the Excel window.Now select Customize the Ribbon from the pop-down menu. The Excel Options Box, check the box Developer to enable it and click on OK. Now, the Developer Tab is visible. Now click on the Visual Basic option in the Developer tab and make a new module to write the program.Developer -> Visual Basic -> Tools -> Macros Now create a Macro and give any suitable name. This will open the Editor window where can write the code. Comparison Operators in Excel:S.No.OperatorsDefinition 1<> Not equal operator is
Read More

A

How to Use for Each Loop in Excel VBA?

A For Each loop is used to execute a statement or a set of statements for each element in an array or collection. Syntax: For Each element In group [ statements ] [ Exit For ] [ statements ] Next [ element ] The For...Each...Next statement syntax has the following three parts: PartDescriptionelement Required (Must be mentioned). Variable is used to iterate through the elements of the collection or array. For collections, the element can only be a Variant variable, a generic object variable, or any specific object variable. For arrays, the element can only be a Variant variable.groupRequired(Must be mentioned). Name of an object collection or array (except an array of user-defined types).statementOptional (May or may not be mentioned). One or more statements are executed on each item in the group. There are 4 basic steps to writing a For Each Next Loop in VBA: Declare a variable.Write the For Each Line with the variable and collection references.Add line(s) of code to repeat for each item in the collection.Write the Next line to terminate the loop. The For…Each block is entered if there is at least one element in the group. Upon entering the loop,
Read More

A

How to Use Do While Loop in Excel VBA?

article_img
A Do…While loop is used when we want to repeat certain set of statements as long as the condition is true. The condition may be checked at the starting or at the end of the loop Flowchart: Uses of Do-While loop: The Do While loop is used in two ways: Do…while loop which checks the condition at the STARTING of the loop.Do…while loop which checks the condition at the END of the loop. Syntax 1: Do While condition [statements] [Exit Do] [statements] Loop Syntax 2: Do While [statements] [Exit Do] [statements] Loop conditionImplementing a Do While loop: Follow the below steps to implement a Do-While loop: Step 1: Define a Macro Private Sub Demo_Loop() End Sub Step 2: Define variables j=2 i=1 Step 3: Write Do While Loop. You can write condition at the beginning or at the end Do While i < 5 Step 4: Write statements to be executed in loop msgbox "Table of 2 is : " & (j*i) i=i+1 Step 5: End loop. Now let's take a look at some of the examples. Example 1: Do…while loop which checks the condition at the STARTING of the loop. The below example uses Do…while loop to check the condition at the starting of the loop. The statements inside the loop are executed, only if the condition is True
Read More

How to Use For Next Loop in Excel VBA?

article_img
If you are familiar with the programming you must have an idea of what a loop is, In computer programming, a loop is a sequence of statements that are repeated until a specific condition is satisfied. In Excel VBA the "For Next" loop is used to go through a block of code a specific number of times. Syntax: For counter = start to end [step count] [code block to execute] statement 1 statement 2 statement 3 . . statement n Next [counter] Here we can use the counter or any other variable to run them as many times as we need. Example: When you are displaying numbers from 1 to 10 you may want to set the value of a variable to 1 and display it 10 times, increasing its value by 1 on each loop iteration. The same logic is used in VBA. We specify how many times we have to run the loop, and then specify what code should our loop execute each time the loop runs. A loop has 3 parts the first one is an initialization, the second is the condition under which the loop runs, and the last is increment or decrement. The flow of the control in for loop:The For step is executed first. This step allows you to initialize any loop control variables and increment the step counter variable.Then the second
Read More

How to Get Length of Array in Excel VBA?

article_img
We use UBound and LBound functions to get the length of an Array in Excel VBA. In this article, we will discuss them in detail. Syntax: UBound() function UBound (arrayname, [ dimension ]) Parameters: arrayname: required. Array variable namedimension: optional Returns: Return upper limit of an array dimension. Syntax: LBound() Function LBound (arrayname, [ dimension ]) Parameters: arrayname : required. Array variable namedimension : optional Returns: Return lower limit of an array dimension Sample Data: VBA Code to get the length of Array (one-dimensional array): Declare Variables: Declaring a customer array with the size of 10. Sub oneDimArrayLength() ' Array variable Declaration Dim customer (1 To 10) As String Assign values to array elements customer(1) = "ANTON" customer(2) = "BERGS" customer(3) = "BOLID" customer(4) = "KOENE" customer(5) = "FRANS" Use UBound function to get the size of an array and Message box to display the result 'Message box to popup length of 1D array MsgBox "Array has " & UBound(customer) & " element(s)." End Sub To Run VBA Code Press Alt+F8 to popup macro window. Select " oneDimArrayLength" and Click Run button. Output VBA Code to get the length
Read More

How to Convert Multiple PowerPoint Files Into Pdf with Excel VBA?

article_img
Often clients need PPT files as PDFs. It helps to view on any device. Use below VBA Macro to convert PowerPoint files from a folder and save them as PDF in the same folder. Implementation: Follow the below steps to convert multiple PowerPoint files into PDFs using Excel VBA: Step 1: Open Excel. Step 2: Type text “Folder Path” in cell “B5” (Image 1). Step 3: Enter your folder full path in cell “C5” (Image 1). Here we have a folder “D:\Excel\29.ppt2pdf\ppt” with two PPT files (Image 2). Image 1Image 2 Step 4: Write below VBA code in your VBE module Sub ppt2pdf_Macro() Dim oPPTApp As PowerPoint.Application Dim oPPTFile As PowerPoint.Presentation Dim onlyFileName As String, folderPath As String, pptFiles As String, removeFileExt As Long Application.ScreenUpdating = FalseInitialize variablesfolderPath = Range("C5").Text & "\" pptFiles = Dir(folderPath & "*.pp*")Check and exit macro if no ppt files are in the folderIf pptFiles = "" Then MsgBox "No files found" Exit Sub End If Do While pptFiles <> ""Assign PowerPoint application to variable Set oPPTApp = CreateObject("PowerPoint.Application") oPPTApp.Visible = msoTrue On Error Resume NextAssign PowerPoint presentation to
Read More
three90RightbarBannerImg