Curious Minds

Clear answers to science and history questions

VBA Loop Through Array: A Complete Guide

· 5 min read · Science

To loop through an array in VBA, use a For...Next loop with an index variable that runs from the array's lower bound to its upper bound, or a For Each...Next loop to iterate over each element directly. Both methods are standard and work with arrays of any data type.

Why Loop Through an Array?

Arrays store multiple values under a single variable name. Looping lets you process each element in turn—summing numbers, filtering text, copying values to a worksheet, or building a report. Without a loop, you would have to write a separate statement for every element, which is impractical for large arrays. Loops make your code shorter, easier to maintain, and adaptable to arrays whose size changes at runtime.

The Two Main Loop Types

VBA offers two primary ways to iterate over an array: the For...Next loop with an index, and the For Each...Next loop. Each has strengths and weaknesses depending on what you need to do.

For...Next with an Index

This loop uses a counter variable that you increment (or decrement) manually. You specify the start and end values, typically the array's lower and upper bounds. Inside the loop, you access elements by index: myArray(i). This approach gives you full control and is the only way to modify elements in place when you need to write back to the array.

For Each...Next

This loop automatically iterates over each element without an explicit index. You write For Each element In myArray and then use element inside the loop. It is cleaner and less error-prone, especially for arrays of objects. However, you cannot easily change the array's contents through the loop variable—assigning to element does not write back to the array (except for object references). Also, For Each always traverses the array from the first to the last element in order.

How to Write a For...Next Loop

Follow these steps to loop through an array using an index:

  1. Declare your array and populate it with values.
  2. Declare a loop counter variable (e.g., Dim i As Long).
  3. Use LBound and UBound functions to get the array's lower and upper bounds. These functions accept the array name and an optional dimension number (for multidimensional arrays).
  4. Write For i = LBound(myArray) To UBound(myArray).
  5. Inside the loop, refer to myArray(i) to read or write the element.
  6. Close with Next i.

Example:

Dim numbers(1 To 5) As Integer
Dim i As Long
numbers(1) = 10
numbers(2) = 20
numbers(3) = 30
numbers(4) = 40
numbers(5) = 50
For i = LBound(numbers) To UBound(numbers)
    Debug.Print numbers(i)
Next i

This prints 10, 20, 30, 40, 50 to the Immediate Window.

How to Write a For Each...Next Loop

The steps are simpler:

  1. Declare your array and populate it.
  2. Declare a variable of the same type as the array elements (use Variant if unsure).
  3. Write For Each element In myArray.
  4. Use element inside the loop.
  5. Close with Next element.

Example:

Dim fruits As Variant
Dim fruit As Variant
fruits = Array("Apple", "Banana", "Cherry")
For Each fruit In fruits
    Debug.Print fruit
Next fruit

This prints each fruit name.

Working with Multidimensional Arrays

For a two-dimensional array, you need nested loops—one for each dimension. Use LBound(array, dimension) and UBound(array, dimension) to get the bounds for each dimension. For example, a 2D array declared as Dim matrix(1 To 3, 1 To 4) As Double requires an outer loop for the first dimension and an inner loop for the second. For Each does not work directly on multidimensional arrays; you must use indexed loops.

Common Pitfalls and How to Avoid Them

  • Assuming zero-based arrays: VBA arrays can have any lower bound. Always use LBound and UBound rather than hard-coding 0 or 1. If you declare Dim arr(1 To 10), the first element is at index 1, not 0.
  • Forgetting to specify the dimension: For multidimensional arrays, omitting the dimension argument in LBound or UBound defaults to the first dimension, which may cause unexpected results.
  • Modifying the loop variable inside the loop: Changing the counter variable inside a For...Next loop can lead to infinite loops or skipped elements. Avoid it.
  • Using For Each on an uninitialized array: If the array is empty (not yet dimensioned), For Each will raise a runtime error. Check with IsArray and ensure it has elements before looping.
  • Confusing array with collection: For Each works on collections too, but collections are 1-based and have different properties. The syntax is similar but not identical.

When to Use Each Loop Type

Choose For...Next when you need the index for calculations, when you need to modify array elements, or when working with multidimensional arrays. Choose For Each...Next when you only need to read each element and want cleaner, more readable code—especially for arrays of objects. For Each is also slightly faster for large arrays of objects because it avoids repeated indexing, though the difference is usually negligible for simple data types.

Frequently Asked Questions

Can I loop through an array backwards?

Yes. Use a For...Next loop with Step -1: For i = UBound(arr) To LBound(arr) Step -1. This is useful when you need to remove elements while iterating, though removing elements from a fixed-size array is not directly possible—you would need to rebuild the array or use a collection.

How do I loop through an array of strings?

The same way as any other array. Declare the array as String (or Variant if using Array()), then use either loop type. For example: For Each s In stringArray or For i = LBound(stringArray) To UBound(stringArray).

What is the difference between LBound and UBound?

LBound returns the smallest valid index (lower bound) of an array dimension, and UBound returns the largest valid index (upper bound). Together they define the range of indices you can safely access.

Can I use a For Each loop to change array values?

No, not for simple data types. The loop variable in For Each is a copy of the element, so assigning to it does not affect the original array. To modify elements, use For...Next with an index and assign to array(i).

How do I loop through a dynamic array?

Dynamic arrays are declared with empty parentheses and later sized with ReDim. Once sized, you can loop through them exactly like fixed arrays, using LBound and UBound to get the current bounds. Always ReDim before looping if the array might be empty.

Is there a performance difference between For...Next and For Each?

For arrays of simple data types, the difference is minimal. For Each can be slightly faster for arrays of objects because it avoids repeated indexing, but for most practical purposes either is fine. Choose based on readability and whether you need the index.

In this article
  1. Why Loop Through an Array?
  2. The Two Main Loop Types
  3. How to Write a For...Next Loop
  4. How to Write a For Each...Next Loop
  5. Working with Multidimensional Arrays
  6. Common Pitfalls and How to Avoid Them
  7. When to Use Each Loop Type
  8. Frequently Asked Questions