Tabellab

Why Tables Beat Plain Ranges

Lesson 1 of 7Reading

The question that eats half your macro

Most VBA written against a plain range exists to answer one question: where does the data stop? You write Cells(Rows.Count, "A").End(xlUp).Row, you quietly assume column A is never empty, and one morning the macro processes 40 rows out of 900 and reports a total that is wrong by five figures. Nothing errors. Nobody notices for a week. An Excel Table removes the question instead of answering it better.

The difference in five lines

' Plain range - a guess dressed up as code
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Set dataRange = ws.Range("A2:F" & lastRow)

' Table - the object states its own extent
Set dataRange = ws.ListObjects("tblSales").DataBodyRange

In the object model an Excel Table is called a ListObject - Microsoft's older internal name for it, which is why the ribbon says Table and the code says ListObject.

Run this and watch the two answers disagree

Paste the whole thing into a standard module (Alt+F11, then Insert - Module) and press F5. It builds its own sheet and its own data, so nothing needs preparing. Two late entries deliberately have no order number - exactly what real exports look like.

Option Explicit

Sub BuildSalesTableDemo()
    Dim ws As Worksheet
    Dim lo As ListObject
    Dim rowsData As Variant
    Dim parts As Variant
    Dim r As Long
    Dim lastWritten As Long
    Dim guessedLastRow As Long
    Dim guessedTotal As Double
    Dim tableTotal As Double
    Dim msg As String

    rowsData = Array( _
        "Order|Region|Product|Amount", _
        "A-1001|Zurich|Keyboard|89.90", _
        "A-1002|Bern|Monitor|249.00", _
        "A-1003|Zurich|Mouse|29.50", _
        "A-1004|Basel|Keyboard|89.90", _
        "A-1005|Bern|Docking station|179.00", _
        "A-1006|Zurich|Monitor|249.00", _
        "A-1007|Basel|Mouse|29.50", _
        "A-1008|Bern|Keyboard|89.90", _
        "|Zurich|Monitor|249.00", _
        "|Basel|Docking station|179.00")

    Application.ScreenUpdating = False

    On Error Resume Next
    Application.DisplayAlerts = False
    ThisWorkbook.Worksheets("TableDemo").Delete
    Application.DisplayAlerts = True
    On Error GoTo 0

    Set ws = ThisWorkbook.Worksheets.Add( _
        After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
    ws.Name = "TableDemo"

    For r = LBound(rowsData) To UBound(rowsData)
        parts = Split(rowsData(r), "|")
        ws.Cells(r + 1, 1).Value = parts(0)
        ws.Cells(r + 1, 2).Value = parts(1)
        ws.Cells(r + 1, 3).Value = parts(2)
        If r = LBound(rowsData) Then
            ws.Cells(r + 1, 4).Value = parts(3)
        Else
            ws.Cells(r + 1, 4).Value = Val(parts(3))
        End If
    Next r

    lastWritten = UBound(rowsData) - LBound(rowsData) + 1

    Set lo = ws.ListObjects.Add( _
        SourceType:=xlSrcRange, _
        Source:=ws.Range("A1:D" & lastWritten), _
        XlListObjectHasHeaders:=xlYes)

    lo.Name = "tblSalesDemo"
    lo.TableStyle = "TableStyleMedium2"
    ws.Columns("A:D").AutoFit

    guessedLastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    guessedTotal = Application.Sum(ws.Range("D2:D" & guessedLastRow))
    tableTotal = Application.Sum(lo.ListColumns("Amount").DataBodyRange)

    Application.ScreenUpdating = True

    msg = "Rows the last-row trick finds: " & (guessedLastRow - 1) & vbCrLf & _
          "Rows the table knows about:    " & lo.ListRows.Count & vbCrLf & vbCrLf & _
          "Total over the guessed range: " & Format$(guessedTotal, "#,##0.00") & vbCrLf & _
          "Total over the table column:  " & Format$(tableTotal, "#,##0.00")

    Debug.Print msg
    MsgBox msg, vbInformation, "Same sheet, two different answers"
End Sub

Reading it line by line

  • rowsData = Array(...) holds the sample rows as pipe-separated text; Split cuts each line into four fields.
  • Val(parts(3)) converts the amount. Val always reads . as the decimal point, so the numbers come out the same on a German or French system, where CDbl would fail.
  • The On Error Resume Next block around .Delete makes the macro re-runnable: an existing sheet is removed, and the missing-sheet error is ignored if there is none.
  • ws.ListObjects.Add turns the block into a table. xlYes says row 1 holds the headers - get it wrong and your columns are called Column1 to Column4.
  • lo.Name replaces the automatic Table1 with an address that survives inserted rows and renamed sheets.
  • lo.ListRows.Count and lo.ListColumns("Amount").DataBodyRange ask the table what it holds. No search, no assumption, no arithmetic.

The trap: End(xlUp) only ever looks at one column

The message box puts the two answers side by side: the trick finds 8 rows, the table reports 10, and the totals differ by 428.00. End(xlUp) walks up column A and stops at the first cell with anything in it, so the two rows with no order number are invisible to it - although their amounts are perfectly real. This is the most expensive bug in beginner VBA, because it returns a plausible number instead of an error. Change "A" to "D" in that line and the guess suddenly agrees, which is exactly the problem: the answer depends on the column you happened to pick.

What else a table hands you at no cost

  • It grows by itself. Type in the row underneath and the table takes it in, with formulas, formatting and filters.
  • Its parts are separate objects - header row, data body and totals row, none of them counted by hand.
  • Formulas read like sentences: =[@Amount]*0.081 instead of =D2*0.081.
  • Charts and PivotTables built on it follow it as it grows, with no code at all.

When a table is the wrong choice

Tables hold no merged cells and no stacked header rows - no loss, since neither belongs in source data. They are also wrong for a finished report with subtotals and spacer rows. Keep the raw list in a table and build the report from it.

Getting hold of it from anywhere

Dim lo As ListObject

' A table name is unique in the whole workbook, so this finds it
' no matter which sheet somebody dragged it onto
Set lo = ThisWorkbook.Worksheets("TableDemo").ListObjects("tblSalesDemo")

Debug.Print lo.ListRows.Count; " data rows"; " in "; lo.Range.Address
Name every table the second you create it, with a tbl prefix. Table1, Table7 and Table23 scattered over nine sheets is how a workbook becomes unmaintainable.

How it goes on

The next lesson maps the model properly - Range, HeaderRowRange, DataBodyRange - including the case that breaks the macro above: an empty table, where DataBodyRange is Nothing. After that come converting existing ranges, adding and deleting rows, structured references, reading a table into an array in one statement, and filtering and sorting from code.

Who this lesson is for, and the bug it removes

This lesson is for anyone who has written, recorded or inherited an Excel macro that works on "the data" without being told where the data is. If you have ever copied the line Cells(Rows.Count, "A").End(xlUp).Row from a forum, you are exactly the reader we have in mind. That line is in a huge share of the VBA that runs in finance, sales and operations teams, and it works most of the time. The trouble is the rest of the time: when the column it looks at has a gap at the bottom, the macro quietly processes fewer rows than exist, prints a plausible total and moves on. No error, no warning, just a number that is wrong.

Excel Tables, which VBA calls ListObjects, fix this at the root. A table knows its own header row, its own data rows and its own columns, and it grows when you add data underneath it. Instead of asking "where does my data stop?", your code asks the table "what do you contain?" and gets a correct answer every time. The free lab above shows the bug in action on a small sales list. This article walks through the same example in more depth, shows the formulas you can use to prove which answer is right, and gives you a checklist for moving existing macros from plain ranges to tables.

The core idea: an object that states its own size

A plain range is just an address, such as A1:D11. Nothing about it says that row 11 is the last row of your data, so every macro has to work that out. The usual way is to jump from the bottom of the sheet upwards in one column and take the first filled cell as the end. That is a guess based on one column, and it is only as good as that column.

A table is different. When you convert a block of cells into a table with Ctrl+T, Excel creates a ListObject with a name, a header row, a data body and, optionally, a totals row. Each of those parts is a separate Range you can ask for in code. The table also tracks its own size: type a value in the row directly below it and the table expands to include that row, carrying formulas and formatting with it. Delete rows inside it and it shrinks. Your code never has to count.

' Plain range: the extent is a guess based on one column
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
Set amounts = ws.Range("D2:D" & lastRow)

' Table: the extent is a property of the object
Set amounts = ws.ListObjects("tblSalesDemo").ListColumns("Amount").DataBodyRange

Both versions produce a Range called amounts that you can sum, loop over or copy. The difference is where the size comes from. In the first version it comes from whatever happens to be in column A at the time. In the second it comes from the table itself, so it includes every row that belongs to the table, whatever is in any particular cell.

Anatomy of a ListObject: tblSalesDemoOrderRegionProductAmountA-1001ZurichKeyboard89.90A-1002BernMonitor249.00A-1003ZurichMouse29.50โ€ฆโ€ฆโ€ฆโ€ฆ(blank)ZurichMonitor249.00(blank)BaselDocking station179.00Total1,433.70lo.HeaderRowRangethe column nameslo.DataBodyRange10 rows, grows by itselflo.TotalsRowRangeonly if ShowTotals = Truedashed outline = lo.Rangelavender = lo.ListColumns("Amount").DataBodyRange
The parts of a table that VBA can address directly. Each bracket is a separate Range property of the ListObject, and the lavender cells are one column found by its header name.

The diagram shows the four properties you will use most. HeaderRowRange is the row of column names. DataBodyRange is all the data rows, and it is the one most macros need. TotalsRowRange exists only when the totals row is switched on. Range is the whole thing, header to totals. On top of that, every column is a ListColumn object you can reach by header name, so lo.ListColumns("Amount").DataBodyRange is "the Amount values, all of them, nothing else", no matter where that column sits or how many rows there are.

A worked example: ten orders, two missing order numbers

The lab builds a small sales list of ten orders across three regions, then converts it into a table called tblSalesDemo. The last two rows came in late and have no order number, which is very common in real exports: a web shop adds the order ID in a second step, or a manual entry is made before the ID is known. Here is the data as it sits on the sheet, with a column showing which rows the last-row trick can see.

Sheet rowOrderRegionProductAmountSeen by End(xlUp) on column A?
2A-1001ZurichKeyboard89.90yes
3A-1002BernMonitor249.00yes
4A-1003ZurichMouse29.50yes
5A-1004BaselKeyboard89.90yes
6A-1005BernDocking station179.00yes
7A-1006ZurichMonitor249.00yes
8A-1007BaselMouse29.50yes
9A-1008BernKeyboard89.90yes
10(blank)ZurichMonitor249.00no
11(blank)BaselDocking station179.00no

Column A has a value in rows 2 to 9 and is empty in rows 10 and 11. End(xlUp) starts at the very bottom of column A, moves up and stops at row 9, the first filled cell it meets. So the guessed range is D2:D9 and it holds eight amounts. The table, on the other hand, covers rows 2 to 11, because that is the block you converted. Here are the formulas you can type next to the table to check both answers. They use structured references, the table-aware syntax where tblSalesDemo[Amount] means the whole Amount column of that table.

What you wantFormula on the sheetResult
Total of the Amount column=SUM(tblSalesDemo[Amount])1,433.70
Number of data rows=ROWS(tblSalesDemo)10
Filled order numbers=COUNTA(tblSalesDemo[Order])8
Rows with no order number=COUNTBLANK(tblSalesDemo[Order])2
Zurich total=SUMIFS(tblSalesDemo[Amount],tblSalesDemo[Region],"Zurich")617.40
Bern total=SUMIFS(tblSalesDemo[Amount],tblSalesDemo[Region],"Bern")517.90
Basel total=SUMIFS(tblSalesDemo[Amount],tblSalesDemo[Region],"Basel")298.40
What the guessed range adds up to=SUM(D2:D9)1,005.70

The difference between 1,433.70 and 1,005.70 is 428.00, which is exactly the two missing rows: a Zurich monitor at 249.00 and a Basel docking station at 179.00. Notice the two counting formulas. ROWS counts the rows of the table, so it says 10. COUNTA on the Order column counts only filled cells, so it says 8. Whenever those two numbers disagree, any code that finds the end of the data through that column will be wrong. That makes =ROWS(tbl)-COUNTA(tbl[KeyColumn]) a quick health check you can leave on a control sheet.

Region totals: guessed range vs table columnEnd(xlUp) range, 8 rowsTable column, 10 rows0250500750368.40617.40Zurich517.90517.90Bern119.40298.40Basel
Region totals from the same ten rows. The guessed range drops the two late rows, so Zurich is short by 249.00 and Basel by 179.00, while Bern happens to be correct.

The chart shows why this bug is so hard to catch by eye. Bern is identical in both versions, because none of the missing rows are from Bern. If the person checking the report only looks at one region, or compares the total with last month and sees something plausible, nothing looks off. The error depends entirely on which rows happen to have a gap, and that changes from one export to the next.

Here is the macro version of the region totals, written against the table. It uses SumIfs through Application.WorksheetFunction, with the table columns as the ranges, so there is no row number anywhere in the code. It also checks that the table has data before using it, because an empty table returns Nothing for DataBodyRange.

Option Explicit

Sub RegionTotalsFromTable()
    Dim lo As ListObject
    Dim regions As Variant
    Dim i As Long
    Dim total As Double

    Set lo = ThisWorkbook.Worksheets("TableDemo").ListObjects("tblSalesDemo")

    If lo.DataBodyRange Is Nothing Then
        MsgBox "The table has no data rows yet.", vbExclamation
        Exit Sub
    End If

    regions = Array("Zurich", "Bern", "Basel")

    For i = LBound(regions) To UBound(regions)
        total = Application.WorksheetFunction.SumIfs( _
            lo.ListColumns("Amount").DataBodyRange, _
            lo.ListColumns("Region").DataBodyRange, regions(i))
        Debug.Print regions(i), Format$(total, "#,##0.00")
    Next i

    Debug.Print "Data rows: " & lo.ListRows.Count
End Sub

Run the lab macro first so the sheet and table exist, then run this one with F5 and open the Immediate window with Ctrl+G. You should see Zurich 617.40, Bern 517.90, Basel 298.40 and ten data rows. Now type an eleventh order in the row directly under the table and run it again. The table has absorbed the new row, the count goes up to eleven and the totals include it, without a single change to the code.

How to do it in Excel, step by step

  1. Click any cell inside your data block. Make sure the block has one header row, no completely empty rows and no merged cells.
  2. Press Ctrl+T (or go to Insert > Table). Check that the range Excel proposes is right and that "My table has headers" is ticked, then click OK.
  3. With a cell in the table selected, open the Table Design tab (called Table in some versions). In the Table Name box on the left, replace Table1 with a meaningful name such as tblSales and press Enter.
  4. Next to the table, type =SUM(tblSales[Amount]) and =ROWS(tblSales). As you type the opening bracket Excel offers the column names, which confirms the table name is right.
  5. Press Alt+F11 to open the VBA editor, then choose Insert > Module to get a standard module.
  6. Paste or type your macro. Start it with Option Explicit so that misspelled variable names are caught before the code runs.
  7. Get the table by name with Set lo = ThisWorkbook.Worksheets("Sheet1").ListObjects("tblSales"), adjusting the sheet name.
  8. Use lo.DataBodyRange or lo.ListColumns("Amount").DataBodyRange wherever the old code used a range built from a last-row number.
  9. Put the cursor inside the macro and press F8 to step through it line by line, or F5 to run it. Watch the output in the Immediate window (Ctrl+G).
  10. Compare the macro result with the SUM formula on the sheet. They must agree. Then add a row below the table and run it again to prove that the code follows the table.
Excel for Mac supports tables and the ListObject object model in the same way, so everything in this lesson works there too. The VBA editor opens with Option+F11 or via Tools > Macro > Visual Basic Editor, depending on your keyboard settings.

Adding a row from code, a preview

Because the table manages its own size, adding data from VBA does not involve finding the next empty row either. ListRows.Add appends a row at the bottom of the table and returns it as a ListRow, so you can fill it straight away. Using ListColumns(...).Index to pick the column means the code still works if somebody reorders the columns. Lesson 4 covers this properly, including inserting at a position and adding many rows at once.

Dim lo As ListObject
Dim newRow As ListRow

Set lo = ThisWorkbook.Worksheets("TableDemo").ListObjects("tblSalesDemo")
Set newRow = lo.ListRows.Add

newRow.Range(1, lo.ListColumns("Order").Index).Value = "A-1011"
newRow.Range(1, lo.ListColumns("Region").Index).Value = "Bern"
newRow.Range(1, lo.ListColumns("Product").Index).Value = "Mouse"
newRow.Range(1, lo.ListColumns("Amount").Index).Value = 29.5

Excel Tables and ListObjects in VBA course illustration
This course drives real Excel Tables from VBA, from finding them by name to filtering and sorting them in code.

Common mistakes, and how to spot them

  • Finding the last row through a column that can be empty. Spot it by comparing =ROWS(tbl) with =COUNTA(tbl[YourColumn]). If they differ, any End(xlUp) on that column is short. The fix is to stop guessing and use DataBodyRange.
  • Leaving tables called Table1, Table2 and so on. Code like ListObjects(1) or ListObjects("Table3") breaks as soon as someone adds or rebuilds a table. Name every table on creation with a tbl prefix and always refer to it by that name.
  • Assuming DataBodyRange always exists. A table with a header but no data rows returns Nothing, and using it raises error 91. Test If lo.DataBodyRange Is Nothing Then before reading from it.
  • Using lo.Range when you mean the data. Range includes the header row, so a sum over it may still work, but a loop will try to process the column names as data, and a count will be one too high. Use DataBodyRange for data.
  • Referring to columns by number. lo.DataBodyRange.Columns(4) breaks the day someone inserts a column. lo.ListColumns("Amount") keeps working as long as the header text stays the same.
  • Leaving gaps between the table and new data. A table only expands automatically when you type directly in the row below it. A value two rows down stays outside. Spot it by clicking inside the table and checking that the blue resize handle in the bottom-right corner sits under your last row.
  • Putting a finished report into a table. Subtotal rows, blank spacer rows and merged headings do not belong in a table. Keep the raw list as a table and build the report from it.

Quick reference: functions, objects and shortcuts used

ItemTypeWhat it does
Ctrl+TShortcutTurns the selected range into a table (Insert > Table)
Table Design > Table NameRibbonRenames Table1 to something like tblSales
Alt+F11ShortcutOpens the VBA editor
F5 / F8ShortcutRuns the macro / steps through it one line at a time
Ctrl+GShortcutShows the Immediate window where Debug.Print writes
ws.ListObjects("tblSales")VBAGets a table by name from a worksheet
lo.DataBodyRangeVBAThe data rows only, without header and totals (Nothing if the table is empty)
lo.ListRows.CountVBANumber of data rows the table holds
lo.ListColumns("Amount").DataBodyRangeVBAOne column of data, found by its header
lo.HeaderRowRangeVBAThe row of column names
ws.ListObjects.AddVBAConverts a range into a table and returns the new ListObject
=SUM(tblSales[Amount])FormulaStructured reference to a whole table column
=SUMIFS(โ€ฆ), =ROWS(โ€ฆ), =COUNTBLANK(โ€ฆ)FormulaConditional total, row count and blank count, used here to check the macro

Real-world uses

  • Monthly sales exports. A shop system exports orders, and some rows arrive without an order ID or customer number. Pasting the export into a table and summing tbl[Amount] by region gives the full total, whatever is missing.
  • Expense claims. A team adds receipts to a shared list during the month. A macro that books them at month end reads DataBodyRange, so new lines added the day before are never left out.
  • Price lists and lookups. A product list stored as a table can grow without anyone updating a range address in XLOOKUP, data validation or VBA. Code that loads it into a dictionary reads exactly the rows the table holds.
  • Charts and PivotTables fed by macros. If a macro appends rows to a table, every chart and PivotTable built on that table follows it after a refresh, with no named range to maintain.
  • Handing a workbook to colleagues. A macro that uses table names survives people sorting the data, inserting columns or moving the table to another sheet, which is exactly what happens once other people use your file.

What you will build in the rest of this course

Lesson 1 is free. Lessons 2 to 7 are part of the paid course, available for a one-time $9.90, and each one comes with a ready-to-run macro and a check question like the one above.

The ListObject Object Model. You map the whole model: Range, HeaderRowRange, DataBodyRange, ListRows and ListColumns. You also deal with the case that breaks most first attempts, an empty table whose DataBodyRange is Nothing, and write a function that tells you whether a table exists before you use it.

Converting a Range into a Table. You turn existing blocks of data into named, styled tables from code with ListObjects.Add, learn which arguments matter, what the naming rules are, how to make the macro safe to run twice and how to convert a table back to a range or resize it.

Adding and Removing Rows. You append rows with ListRows.Add, fill them by column name, insert at a position, add many rows in one step, delete rows safely and empty a table without destroying its formulas and formatting.

Structured References in VBA. You write formulas like =[@Quantity]*[@Price] from code, fill a whole calculated column with one assignment, refer to a table from other sheets, use the specifiers such as #Data and #Totals, and switch on a totals row.

Reading and Writing Table Data Fast. You read the whole data body into an array in one statement, work on it in memory and write it back in one go, which is the difference between a macro that runs in seconds and one that runs for minutes. You also handle the single-row catch that trips up array code.

Filtering and Sorting a Table. You drive the table's own filter buttons from VBA, clear them again, work only with the visible rows and sort by one or several columns, including by cell colour.

Summary

A plain range makes your macro guess where the data ends, and the usual guess looks at one column only. When that column has a gap, rows disappear from your results without any error. An Excel Table, a ListObject in VBA, states its own size: DataBodyRange is always every data row, ListColumns("Amount") is always the right column, and both follow the table as it grows. In the example, the guess found 8 rows and 1,005.70, while the table found all 10 rows and the correct 1,433.70.

Now scroll up and run the lab macro. Watch the two answers disagree in the message box, then change the column letter in the End(xlUp) line and see the "fix" depend on which column you picked. Answer the check question, and if you want to stop guessing in your own macros for good, the rest of the course shows you how, one table operation at a time.

Frequently asked questions

What is a ListObject in Excel VBA?

A ListObject is the VBA name for an Excel Table, the structure you create with Ctrl+T. It gives your code direct access to the header row, the data rows, the totals row and each column by name.

How do I refer to an Excel Table by name in VBA?

Use the ListObjects collection of the worksheet that holds the table, for example Set lo = Worksheets("Sales").ListObjects("tblSales"). Table names are unique in a workbook, so name each table on creation and always use that name instead of an index number.

How do I find the last row of a table in VBA?

You usually do not need to. lo.DataBodyRange is the full block of data rows and lo.ListRows.Count is the number of rows. If you really need the sheet row number, lo.DataBodyRange.Rows(lo.ListRows.Count).Row gives it, as long as the table is not empty.

Why does End(xlUp) give the wrong last row?

End(xlUp) moves up a single column and stops at the first filled cell. If that column is empty in the last rows of your data, those rows are left out without any error.

Why does DataBodyRange give error 91?

When a table has a header but no data rows, DataBodyRange is Nothing, and using Nothing as a range raises run-time error 91. Check If lo.DataBodyRange Is Nothing Then before reading from it.

Do Excel Tables and ListObjects work on a Mac?

Yes. Excel for Mac supports tables and the ListObject object model, so the code in this lesson runs on both Windows and Mac.

Keep going: Excel Tables (ListObjects)

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. The ListObject Object Model
  2. Converting a Range into a Table
  3. Adding and Removing Rows
  4. Structured References in VBA
  5. Reading and Writing Table Data Fast
  6. Filtering and Sorting a Table

Buy course โ€” CHF 9.90 See the full course

Knowledge check

Your data has a blank cell in the key column of the last row. What does Cells(Rows.Count, "A").End(xlUp).Row return?

Continues in this course
  • The ListObject Object Model
  • Converting a Range into a Table
  • Adding and Removing Rows
  • Structured References in VBA
  • Reading and Writing Table Data Fast
  • Filtering and Sorting a Table

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

Buy course โ€” CHF 9.90