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.
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.
| A | B | C | D | E | |
|---|---|---|---|---|---|
| 1 | EmpID | Name | Department | Start date | Salary |
| 2 | E101 | Nora Hill | Finance | 14-Mar-2019 | 52000 |
| 3 | E102 | Omar Said | Sales | 02-Sep-2021 | 47500 |
| 4 | E103 | Petra Novak | IT | 11-Jan-2017 | 61000 |
| 5 | E104 | Quinn Park | Sales | 20-Jun-2023 | 44000 |
| 6 | E105 | Rita Gomez | Finance | 05-Oct-2020 | 49800 |
The Staff sheet: a table named tblStaff in A1:E6
The parts of a ListObject
| Property | What it returns | For tblStaff |
|---|---|---|
| Range | The whole table, headers included (and totals if shown) | A1:E6 |
| HeaderRowRange | The header row | A1:E1 |
| DataBodyRange | The data rows only | A2:E6 |
| ListColumns("Salary") | One column object | column E |
| ListColumns("Salary").DataBodyRange | The data cells of that column | E2:E6 |
| ListRows(2) | The second data row object | row 3 of the sheet |
| TotalsRowRange | The totals row, if ShowTotals is True | none 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.
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 SubListObjects.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.
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:
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 SubThe 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.
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 SubnewRow.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:
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| A | B | C | D | E | |
|---|---|---|---|---|---|
| 1 | EmpID | Name | Department | Start date | Salary |
| 2 | E101 | Nora Hill | Finance | 14-Mar-2019 | 52000 |
| 3 | E102 | Omar Said | Sales | 02-Sep-2021 | 47500 |
| 4 | E103 | Petra Novak | IT | 11-Jan-2017 | 61000 |
| 5 | E104 | Quinn Park | Sales | 20-Jun-2023 | 44000 |
| 6 | E105 | Rita Gomez | Finance | 05-Oct-2020 | 49800 |
| 7 | E106 | Sam Walker | IT | 01-Dec-2026 | 53500 |
| 8 | E107 | Tara Quinn | Finance | 02-Dec-2026 | 50200 |
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:
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 Sublo.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).
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 SubListColumns("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.
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 SubWith 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.
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[@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
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 SubThe 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.
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 Sublo.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.
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
DataBodyRangeof an empty table without checking forNothing. - Confusing table positions with sheet positions:
ListRows(1)is sheet row 2 here, andListColumns("Salary").Indexcounts from the table's first column, not from column A. - Leaving the default name
Table1, then breaking formulas when another table becomesTable1. - 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.Addalways 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?
An empty table has no body range, so test If lo.DataBodyRange Is Nothing first.
2. Which statement adds a new row to the bottom of a table and expands it?
ListRows.Add returns the new ListRow and copies formats and calculated columns.
3. In tblStaff (headers in row 1), which sheet row is lo.ListRows(2)?
ListRows counts data rows only, so the second data row is on sheet row 3.
4. What does the formula =[@Salary]/12 inside the table mean?
The @ sign means "this row" in a structured reference.
5. Why is lo.ListColumns("Salary").DataBodyRange better than Range("E2:E6")?
Table-based references adapt automatically; hard-coded addresses do not.