Sub topic 14
Automating table creation with VBA
This chapter shows how to create, configure and remove an Excel table from VBA. It assumes you can open the Visual Basic Editor (Alt+F11), insert a module and run a macro. It also assumes you know how to create a table by hand and what a table name and a total row are.
Tables are ListObjects
In VBA, an Excel table is a ListObject. Each worksheet has a ListObjects collection that holds its tables. You use the same settings you set on the Ribbon, but as properties:
| Ribbon setting | ListObject property |
|---|---|
| Table Name box | `Name` |
| Table Styles gallery | `TableStyle` |
| Total Row check box | `ShowTotals` |
| Header Row check box | `ShowHeaders` |
| Convert to Range | `Unlist` method |
Creating a table
The ListObjects.Add method takes a source type, a source range, a link argument that you can leave empty, and a flag that says whether the data has headers. The macro below converts the block of data around A1 into a table.
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 SubHere is what each part does:
ws.Range("A1").CurrentRegionselects the contiguous block of data around A1, stopping at the first fully blank row and column. This is the same range Excel guesses when you press Ctrl+T.xlSrcRangesays the source is a normal range.xlYessays the first row holds headers. If you usexlNo, Excel inserts a new header row with names such as Column1.TableStyletakes the name of a built-in style as text.ShowTotals = Trueadds the total row below the data.
Common errors
- Run-time error 1004 on a second run. The range is already part of a table. A cell can belong to only one table, so check first or delete the old table.
- Name conflict. Table names must be unique in the workbook and cannot contain spaces. Setting
Nameto a name that already exists fails. - Wrong range. If a blank row or column splits your data,
CurrentRegionreturns only part of it. Prepare the data first, as you do for the manual method. - Duplicate or blank headers. Excel renames duplicate headers and fills blank ones with a name such as Column1. Check that the header text is what you intended.
Making the macro safe to re-run
Instead of assuming the table does not exist, test for it by looping through the collection.
Function TableExists(ws As Worksheet, tableName As String) As Boolean
Dim lo As ListObject
For Each lo In ws.ListObjects
If lo.Name = tableName Then
TableExists = True
Exit Function
End If
Next lo
End Function
Sub CreateSalesTableOnce()
Dim ws As Worksheet
Set ws = ActiveSheet
If TableExists(ws, "SalesTable") Then
MsgBox "SalesTable already exists."
Exit Sub
End If
With ws.ListObjects.Add(xlSrcRange, ws.Range("A1").CurrentRegion, , xlYes)
.Name = "SalesTable"
.TableStyle = "TableStyleMedium2"
.ShowTotals = True
End With
End SubUsing the table from VBA
Once the table exists, you can refer to it by name and read its parts.
Sub ShowTableInfo()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects("SalesTable")
Debug.Print "Data rows: " & tbl.ListRows.Count
Debug.Print "Data range: " & tbl.DataBodyRange.Address
Debug.Print "Amount column: " & tbl.ListColumns("Amount").DataBodyRange.Address
End SubListRows.Count excludes the header and total rows, so it matches the number of records. Because the table grows automatically, this count stays correct after you add data.
Converting back to a range
The Unlist method does what the Convert to Range command does. The data and formatting stay, and the table structure goes away.
Sub ConvertSalesTableToRange()
ActiveSheet.ListObjects("SalesTable").Unlist
End SubFormulas that used structured references are rewritten as ordinary cell references, so they keep working.
Exercise
A macro calls ListObjects.Add on A1:D50 and fails with error 1004 on its second run. Why does it fail, and how can you prevent it?
Show answer
The first run turned A1:D50 into a table, and a cell cannot belong to two tables, so the second Add overlaps the existing table. Prevent it by checking whether a ListObject with that name already exists (for example with a loop over ws.ListObjects) and exiting or skipping the creation if it does.
Exercise
Which argument value makes ListObjects.Add treat the first row of the source range as headers, and what happens if you pass xlNo instead?
Show answer
xlYes treats the first row as headers. With xlNo, Excel adds a new header row above the data and fills it with default names such as Column1, Column2 and so on.