Who this lesson is for
Your macro works. It just takes forever. You press the button, the screen flickers, Excel shows "Not Responding" in the title bar and you wait. On a hundred rows nobody noticed; on twenty thousand rows the same macro has become something you start before lunch. If that sounds familiar, the cause is almost certainly not your computer and not VBA itself. It is the way the code talks to the worksheet, one cell at a time.
This free lesson shows you, with a benchmark you run yourself, why cell-by-cell loops are slow and what the alternative looks like. It is written for anyone who already writes loops in VBA, whether for invoices, stock lists, survey exports or month-end clean-ups, and wants them to finish in a moment instead of minutes. You do not need any new tools: the fix is a pattern of three lines that works in every version of Excel that runs VBA.
The core idea: two programs and a border
VBA and the Excel worksheet are separate pieces of software. Your variables live in VBA's memory. The cells live inside Excel's calculation and display engine. Every time your code says ws.Cells(r, 1).Value, VBA has to ask Excel for that value and wait for the answer, and every time it assigns to a cell it has to hand the value across and let Excel store it, check dependent formulas and possibly fire events. Each of these trips is small. The cost comes from making tens of thousands of them.
Working with a value that is already in a VBA variable has none of that overhead. So the strategy is simple: cross the border as few times as possible. Read the whole block of cells into memory in one trip, do all the arithmetic there, and write the whole block back in a second trip. The number of rows then barely affects the number of crossings, which stays at two.
The worked example: 20,000 order lines
The benchmark in the lesson builds its own test data on a sheet called Speed Demo: a quantity in column A, a unit price in column B, and an empty Total column C to be filled with quantity × price. MakeDemoData creates the numbers with a simple repeating pattern, so you can check them by hand. Here are the first rows and the totals for the full set:
| Sheet row | A: Quantity | B: Unit price | C: Total | How A and B were made (r = row − 1) |
|---|---|---|---|---|
| 2 | 2 | 5.05 | 10.10 | (1 Mod 25) + 1, 4.95 + (1 Mod 40) / 10 |
| 3 | 3 | 5.15 | 15.45 | (2 Mod 25) + 1, 4.95 + (2 Mod 40) / 10 |
| 4 | 4 | 5.25 | 21.00 | (3 Mod 25) + 1, 4.95 + (3 Mod 40) / 10 |
| 5 | 5 | 5.35 | 26.75 | (4 Mod 25) + 1, 4.95 + (4 Mod 40) / 10 |
| 6 | 6 | 5.45 | 32.70 | (5 Mod 25) + 1, 4.95 + (5 Mod 40) / 10 |
| … | … | … | … | pattern repeats every 25 quantities and 40 prices |
| 41 | 16 | 4.95 | 79.20 | (40 Mod 25) + 1, 4.95 + (40 Mod 40) / 10 |
| Rows 2–20001 | =SUM(A2:A20001) → 260,000 | =SUM(C2:C20001) → 1,798,000.00 | cross-check: =SUMPRODUCT(A2:A20001,B2:B20001) → 1,798,000.00 |
Both versions of the macro must produce exactly these numbers, and the worksheet formulas in the bottom row are how you prove it. After either run, =SUM(C2:C20001) returns 1,798,000.00, and =SUMPRODUCT(A2:A20001,B2:B20001), which multiplies the two columns row by row and adds the results without using column C at all, returns the same figure. If the two ever disagree, a row was skipped or the wrong range was written. Keep this check in mind for the rest of the course: whenever you rewrite slow code into fast code, prove the output is identical before you celebrate the speed.
Now count the crossings. The slow version reads A and B and writes C for every row, so three trips per row. The fast version reads the block once and writes it once:
| Rows | Cell reads (A and B) | Cell writes (C) | Total crossings, cell by cell | Crossings, array version |
|---|---|---|---|---|
| 1,000 | 2,000 | 1,000 | 3,000 | 2 |
| 5,000 | 10,000 | 5,000 | 15,000 | 2 |
| 10,000 | 20,000 | 10,000 | 30,000 | 2 |
| 20,000 (the benchmark) | 40,000 | 20,000 | 60,000 | 2 |
The two versions side by side
Here is the heart of the benchmark. The slow version is the loop most people write first:
For r = 2 To DEMO_ROWS + 1
ws.Cells(r, 3).Value = ws.Cells(r, 1).Value * ws.Cells(r, 2).Value
Next r
The fast version does exactly the same arithmetic, but on a Variant array:
data = ws.Range("A2").Resize(DEMO_ROWS, 3).Value
For r = 1 To UBound(data, 1)
data(r, 3) = data(r, 1) * data(r, 2)
Next r
ws.Range("A2").Resize(DEMO_ROWS, 3).Value = data
Three details matter. First, data is declared As Variant: assigning a multi-cell range's .Value to it creates a two-dimensional array with one element per cell, rows first and columns second. Second, that array starts at index 1 in both directions, not 0, so sheet row 2 is data(1, …); that is why the loops use different start values. Third, the write-back range is built with the same Resize as the read, so its shape matches the array exactly. A mismatch either truncates the data silently or fills the extra cells with #N/A.
There is one consequence of the round trip that catches people out on real workbooks. .Value reads the results of any formulas in the block, not the formulas themselves, and writing the array back puts those results into the cells as plain values. In the benchmark that is harmless, because columns A to C contain only numbers. In your own sheets, if the block you read includes a column of formulas, writing it back silently replaces every formula with its current result. The safe habit is to read only the columns you need, and to write back only the columns you changed, for example by reading A:B into one array and writing the totals into C from a second, one-column array. If you genuinely need the formulas, read .Formula instead, which returns the formula text.
Memory is rarely the limit. A block of twenty thousand rows by three columns is small for a modern computer, and even blocks of a few hundred thousand cells are normally fine. If you work with far larger ranges, process them in chunks of, for example, fifty thousand rows, which keeps the pattern exactly the same.
Run the benchmark yourself, step by step
- Open a new, empty workbook. The benchmark creates its own sheet, so nothing of yours is at risk. Save it as Excel Macro-Enabled Workbook (*.xlsm) with
F12. - Press
Alt+F11to open the VBA editor, then Insert → Module. - Paste the complete block from the lesson, including
Option Explicit, the two constants and all five procedures. - Choose Debug → Compile VBAProject. If anything is highlighted, a line was cut off while pasting.
- Click inside
BenchmarkCellsVsArrayand pressF5. Wait for the message box with both timings and the speed factor. - Back in Excel, enter
=SUM(C2:C20001)and=SUMPRODUCT(A2:A20001,B2:B20001)in two spare cells (for example in column E) and confirm both show 1,798,000.00. - Change
DEMO_ROWSto 5000 and to 50000 and run it again. Watch how the slow timing grows with the row count while the array timing stays small. - If a run ever takes far too long, press
Ctrl+Break(orEsc) to interrupt it, then choose End.
How to recognise a slow loop in your own code
You do not need to rewrite every macro you own. Look for these patterns inside a For or Do loop that runs over many rows; each one means a crossing, or worse, on every pass:
.Value,.Formulaor.Texton a single cell, read or written once per row. This is the benchmark's pattern and the most common one..Selectand.Activate, usually left over from the macro recorder. They also redraw the screen and are almost never needed; refer to the range directly instead.- Formatting one cell at a time, such as setting
.Interior.Coloror.NumberFormatinside the loop. Format the whole column once before or after the loop. - Copy and paste per row. Collect the rows you need in an array or build one range, and copy once.
- Deleting rows inside the loop. Every deletion shifts the rows below and can trigger recalculation. Later lessons show how to mark rows in memory and remove them in one step.
Before rewriting anything, measure. Wrap the suspect section in two Timer readings and print the difference to the Immediate window (Ctrl+G):
Dim t As Double
t = Timer
' ... the code you want to measure ...
Debug.Print "Took " & Format(Timer - t, "0.000") & " s"
If one loop accounts for nearly all of the time, that loop is the one to convert to an array. If the time is spread thinly across many small steps, the gains will be smaller and the clearest code may be the better choice. The Measuring with Timer lesson later in this course turns this into a proper habit, including how to time sections of a long macro separately.
One more reason the slow version feels worse than its timing suggests: while VBA is busy, Excel cannot respond to the operating system, so Windows may grey the window and add "Not Responding" to the title bar. Nothing is broken; the macro is still working. But users tend to click around or force-close the program at that point, which is another good reason to make long loops short.
Where the time actually goes
The benchmark switches off screen updating and sets calculation to manual for both runs, so the comparison is fair. It is worth knowing what those switches do and do not fix. Redrawing the screen and recalculating dependent formulas are real costs, and switching them off helps any macro. Events are a third cost: a Worksheet_Change handler on the target sheet would run once for every single cell the slow loop writes. But even with all three removed, the slow version still pays the crossing itself, once per cell, and only fewer crossings remove that. The switches make a slow loop less slow; the array makes it a different kind of loop.
The benchmark also restores the user's settings afterwards. It stores Application.ScreenUpdating and Application.Calculation in variables before changing them and writes them back at the end, rather than assuming the user wanted automatic calculation. That small courtesy is a habit worth copying into every macro that changes application settings.

Common mistakes and how to spot them
- Unqualified
Cells.Cells(r, 3)with no sheet in front means the active sheet. Click another tab during a long run and the values land there. Always use a worksheet variable, as inws.Cells(r, 3). - Looping from 0. Arrays read from a range start at 1.
data(0, 1)raises "Subscript out of range". UseFor r = 1 To UBound(data, 1). - Write-back range of the wrong size. If the range is smaller than the array, data is silently cut off; if it is larger, extra cells show
#N/A. Build both with the sameResize. - Forgetting to restore settings. A macro that ends with calculation still on manual leaves the user's formulas frozen. Store the old values and restore them, ideally in an error handler as well.
- Timing the setup as well as the work. If data creation happens inside the timed section, the comparison is meaningless. The benchmark builds the data before starting the clock.
- Assuming fast means correct. Check the output with
=SUMand=SUMPRODUCT, or compare the two result columns with=SUMPRODUCT(--(C2:C20001<>D2:D20001)), which counts mismatching rows and should return 0. - Reading a single cell into an array.
.Valueof a one-cell range is a single value, not an array, soUBoundfails. Later in the course you will see how to handle that case.
Quick reference
| Item | What it does |
|---|---|
data = ws.Range("A2").Resize(n, 3).Value | Reads an n × 3 block into a 2-D Variant array in one go |
ws.Range("A2").Resize(n, 3).Value = data | Writes the whole array back in one go |
UBound(data, 1) / UBound(data, 2) | Number of rows / columns in the array (both start at 1) |
Timer | Seconds since midnight as a decimal; subtract two readings for elapsed time |
Application.ScreenUpdating = False | Stops redrawing while the macro runs |
Application.Calculation = xlCalculationManual | Stops recalculation; store and restore the previous value |
Set ws = ... then ws.Cells(r, c) | Ties every reference to one sheet instead of the active one |
Ctrl+Break (or Esc) | Interrupts a macro that is taking too long |
Ctrl+G, Debug.Print | Immediate window for quick timings and checks |
=SUM(), =SUMPRODUCT() | Prove that the slow and fast versions produced the same numbers |
Real-world uses
- Price and quantity calculations. Exactly the benchmark: line totals, discounts, tax or currency conversion across tens of thousands of rows in one pass.
- Cleaning exported data. Trim spaces, fix upper and lower case, split codes or replace placeholders in a system export without touching each cell individually.
- Flagging rows. Mark duplicates, overdue invoices or out-of-range readings by filling a status column in memory and writing it back once.
- Month-end consolidation. Combine several large blocks into one array and write a single result table, instead of copying row by row.
- Reconciliation. Compare two lists that are each read into an array, which makes nested comparisons practical where cell-by-cell code would take minutes.
What you will build in the rest of this course
This first lesson is free and shows you the payoff. The remaining six lessons are part of the paid course and show you how to get it reliably on real, messy data.
Reading a Range into an Array. You learn exactly what .Value hands you, why the indexes start at 1, how to size a read with the last used row, and how to deal with the single-cell case that breaks naive code.
Doing the Work in Memory. You practise the loops that do the real work: calculating new columns, testing conditions, counting and summarising, all without touching the sheet until the end.
Writing Back in One Shot. You let the array tell you its own size with UBound, so the write-back range always fits, and you write results to a new column or sheet without disturbing the source.
The Application Switches. You use screen updating, calculation and events correctly, read the user's settings first and restore them afterwards, even when an error occurs.
Measuring with Timer. You time sections of your own macros properly, so you rewrite the part that is actually slow instead of guessing.
Common Traps and a Working Template. You deal with filtered rows, merged cells, one-column ranges and empty cells, and finish with a template you can paste into any project.
Summary
Cell-by-cell loops are slow because every cell access crosses the border between VBA and the worksheet. Twenty thousand rows of quantity × price means 60,000 crossings; the array version needs two. Read the block with .Value into a Variant, loop from 1 to UBound, write it back with the same Resize, and prove the result with =SUM and =SUMPRODUCT. If you have not run the benchmark yet, scroll up, paste it into a fresh workbook and press F5. Seeing the factor on your own machine is more convincing than any explanation, and it sets you up for the quiz question at the end of the lesson.
Frequently asked questions
Why is my VBA loop so slow?
Most slow loops read or write worksheet cells one at a time, and each access crosses the boundary between VBA and Excel. Reading the whole range into an array, working there and writing it back once removes almost all of that cost.
How do I read a range into an array in VBA?
Declare a Variant and assign the range's Value to it, for example data = ws.Range("A2:C20001").Value. The result is a two-dimensional array indexed from 1, with rows first and columns second.
How do I write an array back to a worksheet range?
Assign it to a range of exactly the same size, for example ws.Range("A2").Resize(UBound(data, 1), UBound(data, 2)).Value = data. All values are written in a single operation.
Does turning off ScreenUpdating make VBA faster?
Yes, it removes the cost of redrawing, and manual calculation removes recalculation. Neither removes the per-cell cost of reading and writing, which is why arrays are still much faster than a loop over cells.
Do VBA arrays from a range start at 0 or 1?
An array created from Range.Value always starts at 1 in both dimensions, whatever Option Base says. Loop with For r = 1 To UBound(data, 1).
How do I measure how long a VBA macro takes?
Store Timer in a Double before the code runs and subtract it from Timer afterwards. The difference is the elapsed time in seconds, with fractions.
Keep going: Arrays & Performance
This free lab is lesson 1 of 7. Unlock the other 6 hands-on labs, the final exam and your certificate for a one-time CHF 9.90.
- Reading a Range into an Array
- Doing the Work in Memory
- Writing Back in One Shot
- The Application Switches
- Measuring with Timer
- Common Traps and a Working Template