Sub topic 14
Automating table creation with VBA
This chapter assumes you can already create, name and style a table by hand, and that you can record or read a simple VBA macro. You should know how to open the Visual Basic Editor (Alt+F11) and insert a module. In VBA, an Excel table is a ListObject. Everything you did on the Ribbon in earlier chapters has a matching property or method on that object.
The object model in brief
A worksheet has a ListObjects collection, and each ListObject represents one table. Its parts map to the features you already know.
| Table feature | VBA member |
|---|---|
| Table name | `ListObject.Name` |
| Whole table including headers and totals | `ListObject.Range` |
| Data rows only | `ListObject.DataBodyRange` |
| Header cells | `ListObject.HeaderRowRange` |
| Total row cells | `ListObject.TotalsRowRange` |
| Columns and rows | `ListColumns`, `ListRows` |
| Style | `ListObject.TableStyle` |
| Total row on or off | `ListObject.ShowTotals` |
| Convert to range | `ListObject.Unlist` |
DataBodyRange and TotalsRowRange are Nothing when the table has no data rows or no total row. Code that uses them without checking raises error 91, "Object variable or With block variable not set".
Creating a table
The core call is ListObjects.Add. Its arguments, in order, are the source type, the source range, a link source (unused for ranges), a header flag, a destination, and an optional table style name.
Sub CreateSalesTable()
Dim ws As Worksheet
Dim tbl As ListObject
Set ws = ActiveSheet
Set tbl = ws.ListObjects.Add(xlSrcRange, ws.Range("A1").CurrentRegion, , xlYes)
tbl.Name = "SalesTable"
tbl.TableStyle = "TableStyleMedium2"
tbl.ShowTotals = True
End SubThe third argument is skipped with an empty position. The fourth, xlYes, tells Excel that the first row holds headers. The alternatives are xlNo, which makes Excel insert a new header row above your data with names such as Column1, and xlGuess, which lets Excel decide. Prefer xlYes or xlNo in automation. A guess can change when your data changes, and a macro should behave the same way on every run.
Pitfalls of `CurrentRegion`
CurrentRegion returns the block of cells around a cell, bounded by blank rows and blank columns. This is convenient, but it fails in predictable ways:
- A blank row inside the data ends the region early, so the table silently covers only the top part.
- A stray note in the cell directly below or beside the data is pulled into the table.
- If A1 is empty, the region is just A1.
For data you do not control, build the range explicitly from the last used row and column of known columns:
Function SourceRange(ws As Worksheet) As Range
Dim lastRow As Long
Dim lastCol As Long
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
lastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
Set SourceRange = ws.Range(ws.Cells(1, 1), ws.Cells(lastRow, lastCol))
End FunctionThis function assumes column A is filled for every record and row 1 contains the headers. If column A can have gaps, pick a column that is always filled.
Header behavior
With xlYes, Excel treats the first row as headers and converts its values to text. A numeric header such as 2026 becomes the text "2026". Blank header cells are filled with Column1, Column2 and so on. Duplicate headers are made unique by appending a number, so a second Amount becomes Amount2. If your later code looks up tbl.ListColumns("Amount"), check the header names before you rely on them.
Naming rules and conflicts
A table name must be unique in the whole workbook, not only on the sheet. It must start with a letter, an underscore or a backslash, it cannot contain spaces, and it cannot look like a cell reference such as R1C1 or AB12. Assigning an invalid or duplicate name raises runtime error 1004. A table name also cannot match a defined name that already exists in the workbook.
Because a macro may run more than once, guard against re-creating the same table:
Function FindTable(wb As Workbook, tableName As String) As ListObject
Dim ws As Worksheet
Dim lo As ListObject
For Each ws In wb.Worksheets
For Each lo In ws.ListObjects
If StrComp(lo.Name, tableName, vbTextCompare) = 0 Then
Set FindTable = lo
Exit Function
End If
Next lo
Next ws
End FunctionThe function returns Nothing if no table has that name. Table names are not case sensitive, which is why the comparison uses vbTextCompare.
A complete, repeatable macro
This macro combines the checks above. It creates the table if it is missing and otherwise reuses it.
Sub BuildSalesTable()
Dim ws As Worksheet
Dim src As Range
Dim tbl As ListObject
Set ws = ThisWorkbook.Worksheets("Sales")
Set tbl = FindTable(ThisWorkbook, "SalesTable")
If tbl Is Nothing Then
Set src = SourceRange(ws)
If src.Rows.Count < 2 Then
MsgBox "No data found under the header row.", vbExclamation
Exit Sub
End If
Set tbl = ws.ListObjects.Add(xlSrcRange, src, , xlYes)
tbl.Name = "SalesTable"
End If
tbl.TableStyle = "TableStyleMedium2"
tbl.ShowTableStyleRowStripes = True
tbl.ShowTotals = True
tbl.ListColumns("Amount").TotalsCalculation = xlTotalsCalculationSum
End SubThis code assumes a sheet named Sales, the SourceRange and FindTable functions in the same module, and an Amount column. If any of these is missing, the macro stops with a runtime error. Table style names are the built-in names, such as TableStyleLight9 or TableStyleMedium2. Setting TableStyle = "" removes the style.
The flow of the macro looks like this:
Errors you will meet
Most failures come from a few causes:
- Overlap.
ListObjects.Addfails with error 1004 if the source range touches an existing table. Checkws.ListObjectsfirst, or useFindTable. - Merged cells. A range with merged cells in the data body cannot become a table. Unmerge them before you call
Add. - Protected sheets. Creating or resizing a table on a protected sheet fails. Unprotect the sheet in the macro and protect it again at the end.
- Multiple-selection or whole-sheet sources. A source with more than one area is rejected. A whole-column reference works, but produces a very large table, which is rarely what you want.
- Tables and some features. A table cannot be created on a sheet that shares a workbook with a shared-workbook feature turned on, and tables cannot contain array formulas that span several rows. Convert or remove those first.
Working with the table after creation
Adding a calculated column
Add the column, name it, and assign a structured-reference formula to its whole data body in one statement. Excel then treats it as a calculated column.
Sub AddTotalColumn()
Dim tbl As ListObject
Dim col As ListColumn
Set tbl = ThisWorkbook.Worksheets("Sales").ListObjects("SalesTable")
Set col = tbl.ListColumns.Add
col.Name = "Line Total"
col.DataBodyRange.Formula = "=[@Quantity]*[@[Unit Price]]"
End SubThe Formula property takes the English (US) formula syntax regardless of the user's language settings. Use FormulaLocal only if you deliberately want the local syntax. If the table has no data rows, DataBodyRange is Nothing, so add a row first or check for it.
Adding and reading rows
ListRows.Add appends a row at the bottom. When the total row is visible, the new row goes above it. Assign values with a one-dimensional array that matches the column order:
Sub AppendSale()
Dim tbl As ListObject
Dim newRow As ListRow
Set tbl = ThisWorkbook.Worksheets("Sales").ListObjects("SalesTable")
Set newRow = tbl.ListRows.Add
newRow.Range.Cells(1, 1).Value = Date
newRow.Range.Cells(1, 2).Value = "Widget"
newRow.Range.Cells(1, 3).Value = 12
End SubFill only the input columns. Calculated columns fill themselves. This code assumes the first three columns hold a date, a product and a quantity. Adjust the cell indexes to your own layout. For many rows, writing a 2-D array to a Resized range is much faster than calling ListRows.Add in a loop.
Changing the table's extent
tbl.Resize takes a new range that must include the header row and cannot move the header to a different row:
tbl.Resize tbl.Range.Resize(tbl.Range.Rows.Count + 10)Removing the table
Two methods look similar and do very different things:
tbl.Unlistconverts the table to a plain range and keeps data and formatting, as the Convert to Range command does. Structured references in formulas are rewritten as ordinary cell references.tbl.Deleteremoves the table and the data in it.
Sub ConvertSalesTableToRange()
ActiveSheet.ListObjects("SalesTable").Unlist
End SubChoosing between macro and manual steps
A macro pays off when you build the same table repeatedly, such as every month from an exported file. It also helps when a team must get identical names and styles. For a one-off table, Ctrl+T is faster and carries no risk of macro errors. Keep the macro small: create the table, name it, style it, and leave analysis to formulas that use structured references, which keep working as the table grows.
Exercise
A macro uses ws.ListObjects.Add(xlSrcRange, ws.Range("A1").CurrentRegion, , xlYes) and creates a table that stops at row 40, although the data runs to row 200. Name the likely cause and one way to fix it.
Show answer
A blank row at row 41 ends the CurrentRegion early, because CurrentRegion stops at fully blank rows and columns. Fix the data by removing the blank row, or build the source range explicitly from the last used row, for example with ws.Cells(ws.Rows.Count, "A").End(xlUp).Row, and pass that range to ListObjects.Add.
Exercise
What is the difference between ListObject.Unlist and ListObject.Delete, and which one matches the Convert to Range command?
Show answer
Unlist turns the table into a plain range and keeps the data, so it matches Convert to Range. Delete removes the table together with the data in its cells.
Exercise
Why does tbl.ListColumns("Line Total").DataBodyRange.Formula = "=[@Quantity]*[@[Unit Price]]" raise error 91 on a table that was just created from a header row only?
Show answer
A table with no data rows has no data body, so DataBodyRange is Nothing and the assignment fails. Check that tbl.DataBodyRange Is Nothing is False first, or add a row with tbl.ListRows.Add.