VBA course · Lesson 24 of 33

Excel tables in VBA: working with ListObjects

Create Excel tables from VBA, add rows, read columns, loop through records, filter, sort, resize and use structured references with the ListObject object.

Intermediate 18 min read

An Excel table (created with Insert > Table or Ctrl+T, also on Mac) is a list that knows its own size. It grows when you add a row, it carries its formatting and formulas down automatically, and formulas can refer to it by name: =SUM(tblStaff[Salary]) instead of =SUM(D2:D57). For VBA this is wonderful news. Most of the "where does the data end?" code from Find the last row and build dynamic ranges in VBA disappears, because the table tells you.

In VBA a table is a ListObject. Every worksheet has a ListObjects collection, and each table in it has parts you can reach directly: its header row, its body, its columns, its rows and its totals row. This lesson walks through all of them with a staff list.

ABCDE
1EmpIDNameDepartmentStart dateSalary
2E101Nora HillFinance14-Mar-201952000
3E102Omar SaidSales02-Sep-202147500
4E103Petra NovakIT11-Jan-201761000
5E104Quinn ParkSales20-Jun-202344000
6E105Rita GomezFinance05-Oct-202049800

The Staff sheet: a table named tblStaff in A1:E6

The parts of a ListObject

PropertyWhat it returnsFor tblStaff
RangeThe whole table, headers included (and totals if shown)A1:E6
HeaderRowRangeThe header rowA1:E1
DataBodyRangeThe data rows onlyA2:E6
ListColumns("Salary")One column objectcolumn E
ListColumns("Salary").DataBodyRangeThe data cells of that columnE2:E6
ListRows(2)The second data row objectrow 3 of the sheet
TotalsRowRangeThe totals row, if ShowTotals is Truenone yet

Notice that ListRows(1) is the first data row, not the header. And row numbers inside the table are not sheet row numbers: ListRows(2) lives in sheet row 3.

Creating a table from VBA

If your macro produces a list, for example from an import, turning it into a table makes everything afterwards easier.

VBA
Option Explicit

Sub MakeStaffTable()
    Dim ws As Worksheet
    Dim lo As ListObject

    Set ws = ThisWorkbook.Worksheets("Staff")

    ' A range can belong to only one table: stop if one already exists
    If ws.ListObjects.Count > 0 Then
        MsgBox "This sheet already has a table: " & ws.ListObjects(1).Name
        Exit Sub
    End If

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

    lo.Name = "tblStaff"
    lo.TableStyle = "TableStyleMedium2"
    lo.ListColumns("Salary").DataBodyRange.NumberFormat = "#,##0"
    lo.ListColumns("Start date").DataBodyRange.NumberFormat = "dd-mmm-yyyy"
End Sub
Convert the block around A1 into a table named tblStaff

ListObjects.Add returns the new table, so we keep it in the variable lo and work with that. Always give the table a meaningful name: tblStaff is far easier to refer to than the default Table1, and the name is also what your formulas use. Table names cannot contain spaces and must be unique in the workbook.

Watch out. XlListObjectHasHeaders:=xlYes tells Excel that the first row is a header. If you leave it as xlGuess, Excel may decide your first row is data and add headers called Column1, Column2 and so on.

Referring to an existing table

You can reach a table through its sheet, by position or by name:

VBA
Sub GetTable()
    Dim lo As ListObject

    Set lo = ThisWorkbook.Worksheets("Staff").ListObjects("tblStaff")   ' by name (best)
    Set lo = ThisWorkbook.Worksheets("Staff").ListObjects(1)            ' by position

    ' Without knowing the sheet: a table name is unique in the workbook
    Set lo = Range("tblStaff").ListObject

    Debug.Print lo.Name, lo.Range.Address, lo.ListRows.Count   ' tblStaff  $A$1:$E$6  5
End Sub
Three ways to get hold of the same table

The third form works because every table name is also a defined range name. Range("tblStaff") gives the data body, and its .ListObject property returns the table it belongs to. Without a workbook in front, Range("tblStaff") searches the active workbook, so in larger projects prefer ThisWorkbook.Worksheets(...).ListObjects(...).

Adding a row

Appending is the job tables do best. ListRows.Add inserts a new row at the bottom, expands the table and copies formats and calculated columns down.

VBA
Sub AddEmployee()
    Dim lo As ListObject
    Dim newRow As ListRow

    Set lo = ThisWorkbook.Worksheets("Staff").ListObjects("tblStaff")
    Set newRow = lo.ListRows.Add

    With newRow.Range
        .Cells(1, 1).Value = "E106"
        .Cells(1, 2).Value = "Sam Walker"
        .Cells(1, 3).Value = "IT"
        .Cells(1, 4).Value = DateSerial(2026, 12, 1)
        .Cells(1, 5).Value = 53500
    End With
End Sub
Add a new employee to the end of the table

newRow.Range is the row's cells, from the first to the last column of the table. .Cells(1, 3) means "row 1, column 3 of that row". A clearer version uses column names, so the code still works if someone moves the Department column:

VBA
Sub AddEmployeeByName()
    Dim lo As ListObject
    Dim r As Long

    Set lo = ThisWorkbook.Worksheets("Staff").ListObjects("tblStaff")
    lo.ListRows.Add
    r = lo.ListRows.Count       ' index of the row we just added

    lo.ListColumns("EmpID").DataBodyRange(r).Value = "E107"
    lo.ListColumns("Name").DataBodyRange(r).Value = "Tara Quinn"
    lo.ListColumns("Department").DataBodyRange(r).Value = "Finance"
    lo.ListColumns("Start date").DataBodyRange(r).Value = DateSerial(2026, 12, 2)
    lo.ListColumns("Salary").DataBodyRange(r).Value = 50200
End Sub
Write by column name instead of position
ABCDE
1EmpIDNameDepartmentStart dateSalary
2E101Nora HillFinance14-Mar-201952000
3E102Omar SaidSales02-Sep-202147500
4E103Petra NovakIT11-Jan-201761000
5E104Quinn ParkSales20-Jun-202344000
6E105Rita GomezFinance05-Oct-202049800
7E106Sam WalkerIT01-Dec-202653500
8E107Tara QuinnFinance02-Dec-202650200

tblStaff after both macros: the table has grown to A1:E8

The empty table trap: DataBodyRange is Nothing

When a table has a header but no data rows, DataBodyRange is Nothing. Any code that reads lo.DataBodyRange.Rows.Count then crashes with error 91. Check first:

VBA
Sub ResetTable()
    Dim lo As ListObject
    Set lo = ThisWorkbook.Worksheets("Staff").ListObjects("tblStaff")

    If lo.DataBodyRange Is Nothing Then
        MsgBox "The table is already empty."
    Else
        MsgBox lo.ListRows.Count & " rows will be removed."
        lo.DataBodyRange.Delete      ' keeps the header and the table itself
    End If
End Sub
Count the rows safely and clear a table without deleting it

lo.ListRows.Count is safe on an empty table (it returns 0) and is the better way to count. After DataBodyRange.Delete, the table keeps one empty row on screen, but VBA sees zero rows.

Looping through rows

There are two good ways to visit every record. Looping through ListRows is readable; reading the body into an array is fast (Arrays in VBA: static, dynamic and fast range processing).

VBA
Sub RaiseSalesSalaries()
    Dim lo As ListObject
    Dim lr As ListRow
    Dim deptCol As Long
    Dim salCol As Long

    Set lo = ThisWorkbook.Worksheets("Staff").ListObjects("tblStaff")
    deptCol = lo.ListColumns("Department").Index
    salCol = lo.ListColumns("Salary").Index

    For Each lr In lo.ListRows
        If lr.Range.Cells(1, deptCol).Value = "Sales" Then
            lr.Range.Cells(1, salCol).Value = Round(lr.Range.Cells(1, salCol).Value * 1.03, 0)
        End If
    Next lr
End Sub
Raise every Sales salary by 3% using ListRows

ListColumns("Salary").Index is the column's position inside the table (5 here), which is what lr.Range.Cells(1, ...) expects. Omar's salary becomes 48,925 and Quinn's 45,320.

VBA
Sub SalaryByDepartment()
    Dim lo As ListObject
    Dim data As Variant
    Dim i As Long
    Dim financeTotal As Double

    Set lo = ThisWorkbook.Worksheets("Staff").ListObjects("tblStaff")
    If lo.ListRows.Count = 0 Then Exit Sub

    data = lo.DataBodyRange.Value     ' 2-D array: data(row, column)
    For i = 1 To UBound(data, 1)
        If data(i, 3) = "Finance" Then financeTotal = financeTotal + data(i, 5)
    Next i

    MsgBox "Finance salaries: " & Format(financeTotal, "#,##0")
End Sub
Total salary per department with an array (fast for thousands of rows)

With the original five rows the message shows 101,800 (52,000 + 49,800).

Structured references from VBA

You can write formulas that use table names straight from VBA. If you put a formula into a whole table column, Excel turns it into a calculated column that fills itself for new rows.

VBA
Sub AddFormulas()
    Dim lo As ListObject
    Dim ws As Worksheet

    Set ws = ThisWorkbook.Worksheets("Staff")
    Set lo = ws.ListObjects("tblStaff")

    ' New column at the right end, then a formula for the whole column
    lo.ListColumns.Add.Name = "Monthly"
    lo.ListColumns("Monthly").DataBodyRange.Formula = "=[@Salary]/12"
    lo.ListColumns("Monthly").DataBodyRange.NumberFormat = "#,##0.00"

    ' A formula outside the table that refers to it by name
    ws.Range("H1").Value = "Average salary"
    ws.Range("H2").Formula = "=AVERAGE(tblStaff[Salary])"
End Sub
Add a calculated column and a summary formula

[@Salary] means "the Salary value in this row". Outside the table, tblStaff[Salary] means the whole column. The formula in H2 keeps working as the table grows, without any VBA. Functions such as AVERAGE, SUMIFS and XLOOKUP all accept these references.

Totals row, filtering, sorting and resizing

VBA
Sub TableTools()
    Dim lo As ListObject
    Set lo = ThisWorkbook.Worksheets("Staff").ListObjects("tblStaff")

    ' Totals row with a sum under Salary and a count under Name
    lo.ShowTotals = True
    lo.ListColumns("Salary").TotalsCalculation = xlTotalsCalculationSum
    lo.ListColumns("Name").TotalsCalculation = xlTotalsCalculationCount

    ' Filter: Field is the column position inside the table
    lo.Range.AutoFilter Field:=lo.ListColumns("Department").Index, Criteria1:="Finance"

    ' Remove the filter again (keeps the arrows)
    If lo.AutoFilter.FilterMode Then lo.AutoFilter.ShowAllData

    ' Sort by salary, highest first
    With lo.Sort
        .SortFields.Clear
        .SortFields.Add2 Key:=lo.ListColumns("Salary").DataBodyRange, Order:=xlDescending
        .Header = xlYes
        .Apply
    End With

    lo.ShowTotals = False
End Sub
Show a totals row, filter, sort and resize

The totals row uses SUBTOTAL formulas, so it shows the total of the visible rows while a filter is on. The Field of a table filter is the column position inside the table, which is why we ask the column for its Index instead of counting by hand. FilterMode is True only while rows are hidden; checking it first avoids an error from ShowAllData when nothing is filtered. Sorting and filtering are explained in detail in Find, filter and sort data with VBA.

Resizing a table

Sometimes rows are pasted directly under a table and the table does not grow with them, for example when the paste came from another program or AutoCorrect's automatic expansion is switched off. Resize fixes that. The new range must start in the same header row and keep the same headers.

VBA
Sub GrowTableToData()
    Dim ws As Worksheet
    Dim lo As ListObject
    Dim lastRow As Long

    Set ws = ThisWorkbook.Worksheets("Staff")
    Set lo = ws.ListObjects("tblStaff")

    lo.ShowTotals = False   ' a totals row in the way would block the new rows
    lastRow = ws.Cells(ws.Rows.Count, lo.Range.Column).End(xlUp).Row

    If lastRow > lo.Range.Row + lo.Range.Rows.Count - 1 Then
        lo.Resize lo.HeaderRowRange.Resize(lastRow - lo.HeaderRowRange.Row + 1)
        MsgBox "The table now ends in row " & lastRow & "."
    Else
        MsgBox "Nothing to add."
    End If
End Sub
Absorb rows that were pasted below the table

lo.HeaderRowRange.Resize(n) keeps the header row and the same columns, and stretches the range down to n rows, which is exactly the shape Resize wants. The bottom of the table is lo.Range.Row + lo.Range.Rows.Count - 1, the first row plus the height minus one, a calculation you met in Find the last row and build dynamic ranges in VBA.

Note. Tables, ListObject and structured references work the same way in Excel for Mac. The only limit worth knowing is that tables cannot be used in a workbook that is shared with the old "Shared Workbook" feature; co-authoring in Microsoft 365 is fine.

Common mistakes

  • Reading DataBodyRange of an empty table without checking for Nothing.
  • Confusing table positions with sheet positions: ListRows(1) is sheet row 2 here, and ListColumns("Salary").Index counts from the table's first column, not from column A.
  • Leaving the default name Table1, then breaking formulas when another table becomes Table1.
  • Writing data in the row just below the table with Cells(lastRow + 1, ...). That usually auto-expands the table, but not when AutoCorrect's "include new rows" option is off. ListRows.Add always works.
  • Adding a table over a range that overlaps another table, which raises error 1004.

Check yourself

1. What does lo.DataBodyRange return for a table with headers but no data rows?

2. Which statement adds a new row to the bottom of a table and expands it?

3. In tblStaff (headers in row 1), which sheet row is lo.ListRows(2)?

4. What does the formula =[@Salary]/12 inside the table mean?

5. Why is lo.ListColumns("Salary").DataBodyRange better than Range("E2:E6")?