Tabellab

Why Cell-by-Cell Loops Are Slow

Lesson 1 of 7Reading

Every cell you touch crosses a border

Your macro and the worksheet are two different pieces of software talking to each other. VBA runs in one place, the Excel calculation and display engine in another, and every single time your code reads or writes a cell a message has to travel between them. That trip is tiny, but it is roughly a thousand times more expensive than working with a number already sitting in memory. Do it once and you will never notice. Do it 60,000 times and you will go and make coffee.

Do not take my word for it — measure it

Paste the whole block below into a fresh module and run BenchmarkCellsVsArray. It builds its own sheet of 20,000 rows, multiplies quantity by price the cell-by-cell way, rebuilds the identical data, does the same job through an array, and shows you both timings and the factor between them. Both versions produce exactly the same numbers in column C, and both run with the screen and recalculation switched off, so what you are seeing is purely the cost of talking to the worksheet.

Option Explicit

Private Const DEMO_SHEET As String = "Speed Demo"
Private Const DEMO_ROWS As Long = 20000

Sub BenchmarkCellsVsArray()
    Dim slowSeconds As Double
    Dim fastSeconds As Double
    Dim previousUpdating As Boolean
    Dim previousCalc As XlCalculation
    Dim verdict As String

    previousUpdating = Application.ScreenUpdating
    previousCalc = Application.Calculation
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    MakeDemoData
    slowSeconds = Timer
    SlowVersion
    slowSeconds = Timer - slowSeconds

    MakeDemoData
    fastSeconds = Timer
    FastVersion
    fastSeconds = Timer - fastSeconds

    Application.Calculation = previousCalc
    Application.ScreenUpdating = previousUpdating

    If fastSeconds > 0 Then
        verdict = Format(slowSeconds / fastSeconds, "0") & " times faster"
    Else
        verdict = "too fast for Timer to measure"
    End If

    MsgBox DEMO_ROWS & " rows, same result both times" & vbCrLf & vbCrLf & _
           "Cell by cell: " & Format(slowSeconds, "0.000") & " s" & vbCrLf & _
           "Array:        " & Format(fastSeconds, "0.000") & " s" & vbCrLf & vbCrLf & _
           "The array is " & verdict & ".", vbInformation, "Cells versus array"
End Sub

Sub SlowVersion()
    Dim ws As Worksheet
    Dim r As Long

    Set ws = DemoSheet()

    For r = 2 To DEMO_ROWS + 1
        ws.Cells(r, 3).Value = ws.Cells(r, 1).Value * ws.Cells(r, 2).Value
    Next r
End Sub

Sub FastVersion()
    Dim ws As Worksheet
    Dim data As Variant
    Dim r As Long

    Set ws = DemoSheet()
    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
End Sub

Private Sub MakeDemoData()
    Dim ws As Worksheet
    Dim block() As Double
    Dim r As Long

    Set ws = DemoSheet()
    ws.Cells.ClearContents
    ws.Range("A1:C1").Value = Array("Quantity", "Unit price", "Total")

    ReDim block(1 To DEMO_ROWS, 1 To 2)
    For r = 1 To DEMO_ROWS
        block(r, 1) = (r Mod 25) + 1
        block(r, 2) = 4.95 + (r Mod 40) / 10
    Next r

    ws.Range("A2").Resize(DEMO_ROWS, 2).Value = block
End Sub

Private Function DemoSheet() As Worksheet
    Dim ws As Worksheet
    Dim found As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        If ws.Name = DEMO_SHEET Then Set found = ws
    Next ws

    If found Is Nothing Then
        Set found = ThisWorkbook.Worksheets.Add
        found.Name = DEMO_SHEET
    End If

    Set DemoSheet = found
End Function

Line by line

  • SlowVersion reads two cells and writes one for every row: 60,000 separate crossings of that border.
  • FastVersion does the same arithmetic with two crossings in total. data = ws.Range(…).Value pulls the whole block into a Variant array, the loop works purely in memory, and the last line pushes it all back in one assignment.
  • MakeDemoData runs before each timing, never inside it, so neither version is charged for building the data.
  • previousUpdating and previousCalc store the user's settings before changing them and put them back afterwards. Leaving calculation on manual is a rude thing to do to somebody's workbook.
  • Timer returns the seconds since midnight as a decimal; subtract two readings and you have the elapsed time. If the array run reports zero, it simply finished below Timer's resolution.
  • Raise DEMO_ROWS to 50,000 if your machine is quick. The array version barely notices; the other one grows in a straight line.

Where the time actually goes

  • The crossing itself — the fixed cost of asking Excel a question, paid once per cell, and the only part the array removes.
  • Recalculation — if any formula depends on the cell you just wrote, Excel may recalculate before your next line runs.
  • Redrawing — by default Excel repaints the screen as values change, and painting is slow.
  • Events — a Worksheet_Change handler, if one exists, fires on every single write you make.

The trap: Cells without a sheet in front of it

This one is worth an afternoon. Cells(r, 3) with nothing in front of it does not mean the sheet my data is on; it means the sheet that is active right now. Run such a macro from the VBA editor while a different sheet is on top, or let a user click another tab during a long run, and 20,000 values land in the wrong place — over real data, with no error at all. Qualify every reference with a worksheet variable, exactly as the benchmark does.

' Wrong: whichever sheet is active when this runs gets the values.
For r = 2 To DEMO_ROWS + 1
    Cells(r, 3).Value = Cells(r, 1).Value * Cells(r, 2).Value
Next r

' Right: every reference is tied to one worksheet.
For r = 2 To DEMO_ROWS + 1
    ws.Cells(r, 3).Value = ws.Cells(r, 1).Value * ws.Cells(r, 2).Value
Next r
A rule of thumb: if a loop runs more than about a thousand times and touches the sheet inside the loop, an array will pay for itself. Below that, write whatever is clearest to read.

How it goes on

The benchmark shows the payoff; the rest of the course shows how to get it on real, messy data. The next lessons cover reading a range into an array and the index rules that surprise everyone, doing the work in memory, writing back into a range of exactly the right shape, the Application switches that buy the last few per cent, measuring properly with Timer, and the traps — filtered rows, merged cells, one-column ranges — with a template worth keeping.

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.

Every .Value on a cell crosses a borderSlowVersion: cell by cellVBAmemoryWorksheetcells A:CFastVersion: one blockVBAmemoryWorksheetcells A:Cread A, read B, write C … per row60,000 crossings for 20,000 rowsread blockwrite blockloop runs20,000 timesin heredata = …Value, loop, …Value = data2 crossings for any size
Left: the slow loop asks for two cells and writes one for every row. Right: the array version reads the block once, does all 20,000 multiplications in VBA's memory, and writes the block back once.

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 rowA: QuantityB: Unit priceC: TotalHow A and B were made (r = row − 1)
225.0510.10(1 Mod 25) + 1, 4.95 + (1 Mod 40) / 10
335.1515.45(2 Mod 25) + 1, 4.95 + (2 Mod 40) / 10
445.2521.00(3 Mod 25) + 1, 4.95 + (3 Mod 40) / 10
555.3526.75(4 Mod 25) + 1, 4.95 + (4 Mod 40) / 10
665.4532.70(5 Mod 25) + 1, 4.95 + (5 Mod 40) / 10
…………pattern repeats every 25 quantities and 40 prices
41164.9579.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.00cross-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:

RowsCell reads (A and B)Cell writes (C)Total crossings, cell by cellCrossings, array version
1,0002,0001,0003,0002
5,00010,0005,00015,0002
10,00020,00010,00030,0002
20,000 (the benchmark)40,00020,00060,0002

Round trips to the worksheet: 3 per row vs 2 in total020,00040,00060,000Cell by cellArray (read once, write once)3,00021,000 rows15,00025,000 rows30,000210,000 rows60,000220,000 rowsReads of A and B plus a write to C for every row, against one read and one write of the whole block
Cell by cell, the number of round trips grows in a straight line with the number of rows. The array version needs two at every size, so its bars barely leave the axis.

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

  1. 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.
  2. Press Alt+F11 to open the VBA editor, then Insert → Module.
  3. Paste the complete block from the lesson, including Option Explicit, the two constants and all five procedures.
  4. Choose Debug → Compile VBAProject. If anything is highlighted, a line was cut off while pasting.
  5. Click inside BenchmarkCellsVsArray and press F5. Wait for the message box with both timings and the speed factor.
  6. 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.
  7. Change DEMO_ROWS to 5000 and to 50000 and run it again. Watch how the slow timing grows with the row count while the array timing stays small.
  8. If a run ever takes far too long, press Ctrl+Break (or Esc) to interrupt it, then choose End.
Your timings depend on your computer, your Excel version and what else is open, so they will differ from anyone else's. The factor between the two versions is the number to look at, and it is reliably large.

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, .Formula or .Text on a single cell, read or written once per row. This is the benchmark's pattern and the most common one.
  • .Select and .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.Color or .NumberFormat inside 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.

A rule of thumb from the lesson: if a loop runs more than about a thousand times and touches the sheet inside the loop, an array pays for itself. For a handful of cells, write whatever is clearest.

Illustration of fast VBA array processing compared with slow cell-by-cell loops in Excel
Read the block, work in memory, write the block: the pattern this whole course is built on.

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 in ws.Cells(r, 3).
  • Looping from 0. Arrays read from a range start at 1. data(0, 1) raises "Subscript out of range". Use For 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 same Resize.
  • 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 =SUM and =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. .Value of a one-cell range is a single value, not an array, so UBound fails. Later in the course you will see how to handle that case.

Quick reference

ItemWhat it does
data = ws.Range("A2").Resize(n, 3).ValueReads an n × 3 block into a 2-D Variant array in one go
ws.Range("A2").Resize(n, 3).Value = dataWrites the whole array back in one go
UBound(data, 1) / UBound(data, 2)Number of rows / columns in the array (both start at 1)
TimerSeconds since midnight as a decimal; subtract two readings for elapsed time
Application.ScreenUpdating = FalseStops redrawing while the macro runs
Application.Calculation = xlCalculationManualStops 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.PrintImmediate 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.

  1. Reading a Range into an Array
  2. Doing the Work in Memory
  3. Writing Back in One Shot
  4. The Application Switches
  5. Measuring with Timer
  6. Common Traps and a Working Template

Buy course — CHF 9.90 See the full course

Knowledge check

You switch off ScreenUpdating and set calculation to manual, and the cell-by-cell version is still many times slower than the array version. Why?

Continues in this course
  • 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

Buy the course to unlock the remaining 6 lessons, the exam and the certificate.

Buy course — CHF 9.90