Excel VBA For Loop with Array (5 Examples)

 

How to Open the VBA Macro Editor in Excel

Steps:

  • Go to the Developer tab and select Visual Basic. Alternatively, press Alt + F11.

Launching Visual Basic Editor from the Developer Tab

  • The Visual Basic window will open.
  • From the Insert option, select Module to insert a new code window to enter the code.

Selecting a New Module from the Visual Basic Editor Window


Excel VBA For Loop with Array: 5 Examples


Example 1 – Using a Nested For Loop for Finding Combination Values

We will show all the possible combined values of two numbers that are multiples of 10 where the sum of these two numbers is 90.

Using Nested For Loop Through Array for Finding Combination Values

  • Copy the following code and paste it into the Module, then click on Run to see the output.
Sub Array_with_Nested_ForLoop()
Dim MyArray(5) As Integer
'Declaring Array Element
MyArray(0) = 20
MyArray(1) = 30
MyArray(2) = 40
MyArray(3) = 50
MyArray(4) = 60
MyArray(5) = 70
'Using For Loop
Dim Combination_Value As String
Combination_Value = "Combination Value of arrays which show Total = '90' : "
For x = LBound(MyArray) To UBound(MyArray)
  For j = LBound(MyArray) To UBound(MyArray)
    'Applying If statement
    If MyArray(x) + MyArray(j) = 90 And x <> j Then
      Combination_Value = Combination_Value + "," + CStr(MyArray(x)) _
      + "+" + CStr(MyArray(j))
    End If
  Next j
Next x
'Showing Result in MsgBox
 MsgBox (Combination_Value)
End Sub

VBA Breakdown

  • The code names the subroutine, “Array_with_Nested_ForLoop“.
Sub Array_with_Nested_ForLoop()
  • We declared an integer array “MyArray” that contains six entries. The next 6 lines populate the “MyArray” array with integer values.
Dim MyArray(5) As Integer
MyArray(0) = 20
MyArray(1) = 30
MyArray(2) = 40
MyArray(3) = 50
MyArray(4) = 60
MyArray(5) = 70
  • We declared a string variable “Combination_Value” and initialized it with a starting string value.
Dim Combination_Value As String
Combination_Value = "Combination Value of arrays which show = 90: "
  • We will apply a For loop to go through the “MyArray” array elements from the lower bound to the upper bound. The “x” variable is used as the loop counter.
For x = LBound(MyArray) To UBound(MyArray)
  • We applied a nested For loop to go through the “MyArray” array elements from the lower bound (i.e., the first element) to the upper bound (i.e., the last element). The “j” variable is used as the loop counter.
For j = LBound(MyArray) To UBound(MyArray)
  • Within the inner For loop, an If statement is used to check if the sum of the current element of the “MyArray” array with the index “x” and the current element of the “MyArray” array with the index “j” is equal to 90 and if “x” is not equal to “j“. If the condition in the If statement is met, the two elements are concatenated with a “+” symbol and added to the “Combination_Value” string by using the CStr.  After the inner For loop completes, the outer For loop moves on to the next element of the “MyArray” array and restarts the j value.
If MyArray(x) + MyArray(j) = 90 And i <> j Then       
Combination_Value = Combination_Value + "," + CStr(MyArray(x)) _       
+ "+" + CStr(MyArray(j))     
End If   
Next j 
Next x
  • A MsgBox statement shows the output of the final value of the “Combination_Value” string.
MsgBox (Combination_Value)

Findings by Using Nested For Loop Through Array for Combination Values

Read More: How to Use Excel VBA Nested For Loop


Example 2 – Applying a For Loop to Loop Through a Multidimensional Array in Excel VBA

We will demonstrate an output of some names of multiple age groups based on their particular range of ages.

Applying For Loop with Multidimensional Array in Excel VBA

  • Copy the following code and paste it into the Module, then click on Run to see the output.
Sub ForLoop_MultidimensionalArray()
Dim MyArray(3, 1) As Variant
 'Populating the array
 MyArray(0, 0) = "Ronin"
 MyArray(0, 1) = 8
 MyArray(1, 0) = "Maddison"
 MyArray(1, 1) = 15
 MyArray(2, 0) = "John"
 MyArray(2, 1) = 13
 MyArray(3, 0) = "Jill"
 MyArray(3, 1) = 16
'Declaring variable for showing the list of names at under 15
Dim Under15 As String
Under15 = "Abobe 8 and under 14 participants Name : "
'Declaring variable for showing the list of names at under 20
Dim Under20 As String
Under20 = "Abobe 14 and under 17 participants Name: "
  For i = LBound(MyArray, 1) To UBound(MyArray, 1)
      If MyArray(i, 1) > 8 And MyArray(i, 1) < 14 Then
        Under15 = Under15 + CStr(MyArray(i, 0)) + ",       "
      ElseIf MyArray(i, 1) > 14 And MyArray(i, 1) < 17 Then
        Under20 = Under20 + CStr(MyArray(i, 0)) + ",  "
      End If
  Next i
MsgBox (Under15)
MsgBox (Under20)
End Sub

VBA Breakdown

  • We named the routine “ForLoop_MultidimensionalArray()“.
Sub ForLoop_MultidimensionalArray()
  • The code declares a two-dimensional array named MyArray with 4 rows and 2 columns. The Variant data type is used here to allow the array to hold values of different data types.
Dim MyArray(3, 1) As Variant
  • The code then populates the array with values. The first index of the array (MyArray(x, 0)) holds the name of a participant, and the second index (MyArray(x, 1)) holds their age.
MyArray(0, 0) = "Ronin"
MyArray(0, 1) = 8
MyArray(1, 0) = "Maddison"
MyArray(1, 1) = 15
MyArray(2, 0) = "John"
MyArray(2, 1) = 13
MyArray(3, 0) = "Jill"
MyArray(3, 1) = 16
  • The code declares two variables Under15 and Under20 as strings, which will later hold the names of participants under the age of 15 and 20, respectively:
Dim Under15 As String
Under15 = "Under 15 participants Name : "
Dim Under20 As String
Under20 = "Under 20 participants Name: "
  • The code then uses a nested For loop to iterate through each row of the array and check if the age of the participant falls within a certain range. In this case, if the age of the participant is greater than 8 and less than 14, their name is added to the Under15.  Similarly, if their age is greater than 14 and less than 17, their name is added to the Under20 string.
For i = LBound(MyArray, 1) To UBound(MyArray, 1)
    If MyArray(i, 1) > 8 And MyArray(i, 1) < 14 Then
      Under15 = Under15 + CStr(MyArray(i, 0)) + ",       "
    ElseIf MyArray(i, 1) > 14 And MyArray(i, 1) < 17 Then
      Under20 = Under20 + CStr(MyArray(i, 0)) + ",  "
    End If
Next i
  • The code displays the names of participants under the age of 15 and 20 in separate message boxes:
MsgBox (Under15)
MsgBox (Under20)

Findings by Applying For Loop to Loop Through  Multidimensional Array in Excel VBA


Example 3 – Employing a For Each Loop with an Array to Show All the Values

We will create an array of some names and show each array item by using a “For each loop” with an array.

Employing For Each Loop Through Array in Excel VBA

  • Copy the following code and paste it into the Module, then click on Run to see the output.
Sub ForEach_Loop_Array()
   'Declaring a variable as an array
   Dim MyString(4) As String
   'Populating the array
   MyString(1) = "Robin"
   MyString(2) = "Ronin"
   MyString(3) = "John"
   MyString(4) = "Maddison"
   'Declaring a variant to hold the array element
   Dim Name As Variant
   'Using For Each loop
   For Each Name In MyString
      'Showing each name in the debug window
      Debug.Print Name
   Next Name
End Sub

VBA Breakdown

  • The name of the subroutine is “ForEach_Loop_Array“.
Sub ForEach_Loop_Array()
  • We declared a variable “MyString” as an array of 4 strings. The array is then populated with 4 names.
Dim MyString(4) As String
MyString(1) = "Robin"
MyString(2) = "Ronin"
MyString(3) = "John"
MyString(4) = "Maddison"
  • We declared a variant variable “Name” to hold each element of the “MyString” array.
Dim Name As Variant
  • We will apply a For Each loop to go through each element of the “MyString” array. The “Name” variable is used to hold the value of each element in turn.
For Each Name In MyString
  • Within the loop, the print statement is used to output the value of the “Name” variable to the Immediate window. Now, the Next statement moves to the next element in the array until all elements have been analyzed. Therefore, when the code is performed, the For Each loop revolves around each element of the “MyString” array, assigns the value of each element to the “Name” variable, and outputs each “Name” to the Immediate window using the Debug.Print statement.
Debug.Print Name 
Next Name

Employing For Each Loop Through Array with Findings in Excel VBA

Read More: Excel VBA to Use For Loop with Two Variables


Example 4 – Using a For Next Loop with an Array in Excel VBA


Case 1 – Loop Through a Part of an Array

We want to show a part of the array by using a For next loop.

VBA For Loop Through Part of Array

  • Copy the following code and paste it into the Module, then click on Run to see the output.
Sub ForNextLoop_Through_Part_Array()
   'Declaring a variant array
   Dim MyString(1 To 4) As String
   'Populating the array
   MyString(1) = "Robin"
   MyString(2) = "Ronin"
   MyString(3) = "John"
   MyString(4) = "Madison"
   'Declaring an integer
   Dim j As Integer
   'Using For Nextloop
   For j = 2 To 3
      'Showing the name in the debug window
      Debug.Print MyString(j)
   Next j
End Sub

VBA Breakdown

  • We declared a variable “MyString” as an array of 4 strings, with indexes from 1 to 4. The array is then populated with 4 names.
Dim MyString(1 To 4) As String
MyString(1) = "Robin"
MyString(2) = "Ronin"
MyString(3) = "John"
MyString(4) = "Madison
  • We declare an integer variable “j” that will be used as a loop counter in the For Next loop.
  • Wwe will apply a For Next loop to go through the “MyString” array elements from index 2 to 3. The “j” variable is used as the loop counter.
  Dim j As Integer
   For j = 2 To 3
  • Within the loop, the Print statement is used to output the value of the element of the “MyString” array with the index “j” to the Immediate window. Now, the Next statement moves to the next element in the loop until the specified range has been analyzed. Therefore, when the code is performed, the For Next loop goes through the elements of the “MyString” array with the indexes 2 and 3 and outputs the value of each element to the Immediate window using the Debug.Print statement.
 Debug.Print MyString(j)
   Next j

Findings with VBA For Loop Through Part of Array


Case 2 – Loop Through an Entire Array

We will show each array item with a For next loop through the entire array.

VBA For Loop Through an Entire Array

  • Copy the following code and paste it into the Module, then click on Run to see the output.
Sub ForNextLoop_Through_Entire_Array()
   'Declaring a variant array
   Dim MyString() As String
   'Initializing the array
   ReDim MyString(1 To 4)
   'Populating the array
   MyString(1) = "Robin"
   MyString(2) = "Ronin"
   MyString(3) = "John"
   MyString(4) = "Maddison"
   'Declaring an integer
   Dim j As Integer
   'For Nextloop from the lower bound of the array to _
   the upper bound of the array - the entire array
   For j = LBound(MyString) To UBound(MyString)
      'Showing the name in the immediate window
      Debug.Print MyString(j)
   Next j
End Sub

Findings with VBA For Loop Through Entire Array


Example 5 – Using a For Loop with an Array to Add Data to Another Sheet

We would like to add data to another sheet whose MPG is greater than 20. You will see the output for cars with an MPG greater than 20.

Using For Loop Through an Array and Add Data to Another Sheet

  • Copy the following code and paste it into the Module, then click on Run to see the output.
Sub Add_Data_into_AnotherSheet()
'Declaring array region
MyArray = Sheet2.Cells(4, 2).CurrentRegion
reportrow = 5
'Using For loop
For Row = 2 To UBound(MyArray)
  'Using If statement
  If MyArray(Row, 1) > 20 Then
    For Column = 1 To UBound(MyArray, 2)
     Sheet3.Cells(reportrow, Column) = MyArray(Row, Column)
    Next
     reportrow = reportrow + 1
    End If
Next
End Sub

VBA Breakdown

  • We declared MyArray as a variable and assign data from sheet2 into it.
MyArray = Sheet2.Cells(4, 2).CurrentRegion
reportrow = 5
  • We will apply For loop to go through each row, and using the If statement, we will check the value which is greater than 20. For column operation, we will apply a For loop again to go through each column for adding the data from sheet2 into sheet3.
For Row = 2 To UBound(MyArray)
  'Using If statement
  If MyArray(Row, 1) > 20 Then
    For Column = 1 To UBound(MyArray, 2)
     Sheet3.Cells(reportrow, Column) = MyArray(Row, Column)
    Next
     reportrow = reportrow + 1
    End If
Next

Frequently Asked Questions

With Excel VBA, how do I loop through an array?

Use the For Loop in VBA to iterate through an array (For Next). Also, in order to use both as the loop’s counter, you must be aware of the array’s size (upper and lower bounds). For the most part, the for loop will begin with the first element of the array and loop all the way to the end.

In VBA, can an array be sent to a function?

Arrays can be passed to procedures (Subs, Functions, and Properties) and returned by Functions and Properties (Property Get only).


Download the Practice Workbook


Related Articles

Get FREE Advanced Excel Exercises with Solutions!

Tags:

Bishawajit Chakraborty
Bishawajit Chakraborty

Bishawajit Chakraborty, a Rajshahi University of Engineering & Technology graduate with a B.Sc. in Mechanical Engineering, has been associated with ExcelDemy since 2022. Presently, he is a content developer, specializing in Excel Power Query, Data Analysis and VBA. It is worth mentioning that he has authored more than 90 articles on VBA content development. His profound interest lies in the fields of data analytics and data science. He possesses expertise in VBA, Power BI, machine learning, and Python... Read Full Bio

We will be happy to hear your thoughts

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo