Macro Development: Looping Two Arrays in Excel VBA

Abstract: Optimize Excel VBA macros by looping two arrays simultaneously to process large datasets efficiently without slow cell-by-cell interactions.

Created: 2026-08-17 by
To loop through two arrays in Excel VBA, load the data from ranges C4:C1500 and D4:D1500 into Variant arrays using the Range.Value property. Iterate simultaneously using a For loop with a single index variable to access corresponding elements in both arrays. This approach significantly outperforms cell-by-cell processing for large datasets by minimizing interaction with the worksheet interface.

Why Use Arrays Instead of Cell References?

When developing macros that process thousands of rows, reading and writing directly to cells is extremely slow because each operation triggers a communication between VBA and the Excel application engine. By loading data into memory as an array, you perform all calculations locally within the VBA environment. Once the logic is complete, you write the results back to the worksheet in a single batch operation. This technique is essential for maintaining performance when handling large datasets like the 1500-row range specified in this scenario. For more context on efficient data handling, see Copy Values from Specific Cell Based on Name in Excel Tab, which discusses similar optimization strategies for data retrieval.

Loading Data Into Arrays

The first step is to define the source ranges and transfer their contents into Variant variables. In VBA, only Variant data types can hold multi-dimensional arrays returned from worksheet ranges. You must ensure that the ranges are contiguous and rectangular. If your data contains merged cells or irregular structures, the array loading process may fail or produce unexpected results. Consider the following code snippet for initializing the arrays:
Dim srcRange1 As Range
Dim srcRange2 As Range
Dim arrData1 As Variant
Dim arrData2 As Variant

' Define the specific ranges
Set srcRange1 = ThisWorkbook.Sheets("Sheet1").Range("C4:C1500")
Set srcRange2 = ThisWorkbook.Sheets("Sheet1").Range("D4:D1500")

' Load data into arrays
arrData1 = srcRange1.Value
arrData2 = srcRange2.Value
Note that when you assign a range to a Variant, VBA automatically creates a two-dimensional array. The indices start at 1 for both dimensions, regardless of whether you use Option Base 0 in your module settings. Therefore, the lower bound of the first dimension (rows) is always 1, and the upper bound corresponds to the number of rows in the range.

Iterating Through Both Arrays Simultaneously

Once the data is in memory, you can loop through the arrays using a standard For Next structure. Since both ranges have the same height (from row 4 to 1500), you can use a single counter variable to access elements in both arrays at the same time. This ensures that the value in C4 is processed alongside D4, C5 with D5, and so on. Here is how you structure the loop:
Dim i As Long
Dim rowCount As Long

' Calculate the number of rows
rowCount = UBound(arrData1, 1) - LBound(arrData1, 1) + 1

For i = 1 To rowCount
    ' Access elements using the current index
    Dim val1 As Variant
    Dim val2 As Variant
    
    val1 = arrData1(i, 1)
    val2 = arrData2(i, 1)
    
    ' Perform your logic here
    ' Example: If val1 > 100 Then ...
Next i
Using Long instead of Integer for the loop counter is recommended for performance reasons, especially when dealing with larger datasets. While Integer suffices for small loops, Long handles larger values without overflow risks and is generally faster in modern VBA versions. Always verify that both arrays have the same number of rows before starting the loop to avoid index out-of-bounds errors.

Writing Results Back to the Worksheet

After processing the data, you typically need to return the results to Excel. If you modified the original arrays, you can write them back directly. However, it is often better practice to create a separate result array if you are transforming the data significantly. To write data back efficiently, define a destination range that matches the dimensions of your output array. Assigning the array to the range's Value property updates all cells simultaneously.
Dim destRange As Range
Set destRange = ThisWorkbook.Sheets("Sheet1").Range("E4:E1500")

' Assuming you have a resultArray prepared
destRange.Value = resultArray
This method ensures that the screen does not flicker and that the macro completes rapidly. Avoid updating cells one by one inside the loop, as this negates the performance benefits gained by using arrays in the first place. For related topics on managing workbook structures during such operations, refer to Using VBA to Add Rows and Shift Tables.

Frequently Asked Questions

What happens if my ranges have different numbers of rows?

You cannot iterate through them using a single index unless you pad the smaller array with empty values. It is best to validate the row counts before starting the loop and exit with an error message if they do not match.

Can I use Option Base 0 to change array indexing?

No. When arrays are created from Range.Value properties, they are always one-based (starting at index 1). Option Base only affects dynamically allocated arrays using ReDim statements.

How do I handle empty cells in the arrays?

Empty cells in a range become Empty variants in the array. You should check for this condition using the IsEmpty function or by comparing against vbNullString if you expect text data.

Is it faster to read columns or rows into arrays?

Reading a single column into an array is straightforward. Reading multiple non-contiguous columns requires combining them or reading the entire block and extracting specific columns, which may be slightly slower but still much faster than cell-by-cell access.

What if I need to update the source data while looping?

Modifying the source array does not affect the worksheet until you write it back. If you need real-time feedback, you would have to write back incrementally, but this destroys the performance advantage. Process everything in memory first.

Tags: Excel VBA Macro

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More