VBA LISTOBJECTS

What are ListObjects in VBA?

In VBA (Visual Basic for Applications), a ListObject is a feature introduced in Excel that represents a table. Tables are a powerful way to manage and analyze data in Excel, and ListObject provides a programmatic way to work with tables through VBA code.

  • Definition: A ListObject is essentially a range that has been converted into a table. It has a structured format, with columns having names and the ability to use structured references in formulas.
  • Creating a ListObject: You can create a ListObject by selecting a range of data in Excel and then converting it to a table. You can use VBA ListObjects.Add querytable code to create a ListObject and specify the range.

Consider a set of values in Excel.

VBA ListObjects - Definition Example - 1

Convert these values into a VBA ListObjects table with the VBA code below.

VBA ListObjects - Definition Example - 2

Define a subroutine to create a table in Excel using the VBA ListObjects.Add function. Here, you can also name the table in the function, as shown, and the table is generated.

VBA ListObjects - Definition Example - 2

Thus, a VBA ListObjects table is formed successfully.

Key Takeaways
  • A ListObject is a feature in Excel VBA that represents a table. It provides a programmatic way to work with structured data in Excel.
  • Tables can be created manually in Excel or through VBA using ListObjects.Add method.
  • Tables can be based on a range of data, and the range can dynamically expand or contract.
  • ListObjects support structured references, allowing for easy referencing of table columns and data in formulas.
  • Tables automatically adjust their size to include new data, making them suitable for dynamic datasets.

How To Create Table Format Using ListObjects in Excel VBA?

Here, we learn how to create a table format using the VBA ListObjects table using VBA. Previously, you saw how to convert already existing data into a table.

In this example, you will learn to define both values and convert them into a table in VBA.

  1. Name the subroutine to create a table format using ListObjects.


    How to Create Table Format Using ListObjects in Excel VBA - Step 1

  2. Define the Worksheet containing the table using the Worksheet datatype.


    How to Create Table Format Using ListObjects in Excel VBA - Step 2

  3. Using the VBA Range function, define some values to be printed in the Excel sheet so that it can be transformed into a table.


    How to Create Table Format Using ListObjects in Excel VBA - Step 3

    In row 1, the headers are declared.

  4. Define a Range variable to store the range of the table.


    How to Create Table Format Using ListObjects in Excel VBA - Step 4

    Using the current region function, you can club all non-empty cells in a sequence. It also makes the range more dynamic with the addition of new values.

  5. Define a ListObject and convert the given range into an Excel Table.


    How to Create Table Format Using ListObjects in Excel VBA - Step 5

    Here,
     
    • xlSrcRange represents the range of cells for which we are inserting the table.
    • tableRange represents the destination range.
    • xlYes states the table has headers.
     
    Using the VBA ListObjects.Add function, you can change the given range into a table.

  6. Define the name of your table using the Name function.


    How to Create Table Format Using ListObjects in Excel VBA - Step 6

    Code:

    Sub CreateTableFormat()
    Dim ws As Worksheet
    Set ws = ActiveWorkbook.Sheets(“Sheet5”)
    ‘ Input some sample data or you can manually input in Excel beforehand
    ws.Range(“A1”).value = “ID”
    ws.Range(“B1”).value = “Name”
    ws.Range(“A2”).value = “S01”
    ws.Range(“B2”).value = “John Doe”
    ws.Range(“A3”).value = “S02”
    ws.Range(“B3”).value = “Jane Doe”
    Dim tableRange As Range
    Set tableRange = ws.Range(“A1”).CurrentRegion
    Dim myTable As ListObject
    Set myTable = ws.ListObjects.Add(xlSrcRange, tableRange, , xlYes)
    With myTable
    ‘ Set a table name
    .name = “MyTable”
    End With
    End Sub

  7. Run the above subroutine and then go to “Sheet5” to see the new table created.


    How to Create Table Format Using ListObjects in Excel VBA - Step 7

How to Format Excel Tables with VBA ListObjects?

Learn how to use VBA ListObjects to format Excel tables by following the steps below.

How to format Excel Tables with VBA ListObjects- Step 1a

Select “Visual Basic”. It will open the VBA Editor, which will be empty. In the Editor, select “Insert” on the VBA toolbar.

How to format Excel Tables with VBA ListObjects- Step 1b

Select “Module” in the drop-down.

How to format Excel Tables with VBA ListObjects- Step 1c
  • Step 2: Consider a set of values given below.
How to format Excel Tables with VBA ListObjects - Step 2a

Use “Ctrl+T” to convert it into a table.

How to format Excel Tables with VBA ListObjects - Step 2b
How to format Excel Tables with VBA ListObjects - Step 2c
  • Step 3: Define a subroutine to format Excel tables with VBA ListObjects AutoFilter.
How to format Excel Tables with VBA ListObjects - Step 3
  • Step 4: Define the table and filter the table based on the third column where only the values whose result is false can be seen. The xlAnd operator is also used.
How to format Excel Tables with VBA ListObjects - Step 4

Using the VBA ListObjects.AutoFilter function, only the values with the “FALSE” result will be shown.

  • Step 5: Define another subroutine to remove all the active filters.
How to format Excel Tables with VBA ListObjects - Step 5
  • Step 6: Select the Header which has been filtered. Here, the column with the header “S” has been filtered.
How to format Excel Tables with VBA ListObjects - Step 6
  • Step 7: Check using an If conditional statement whether the FilterMode property of the ListObject returns “TRUE.”
How to format Excel Tables with VBA ListObjects - Step 7

If it is true, then the ShowAllData property is called, which will remove all the filters.

Code:

Sub FilterListObject()
ActiveWorkbook.Sheets(“Sheet3”).ListObjects(“Table3”).Range.AutoFilter Field:=3, Criteria1:= _
“FALSE”, Operator:=xlAnd
End Sub

Sub ClearAllFilters()
Range(“Table3[[#Headers],[S]]”).Select
If ActiveWorkbook.Worksheets(“Sheet3”).FilterMode = True Then
ActiveSheet.ShowAllData
End If
End Sub

  • Step 8: Click “F5” or the “Run” icon on the activity bar in the Excel VBA Editor.

Table when the FilterListObject subroutine is run.

How to format Excel Tables with VBA ListObjects - Step 8a

Table when the ClearAllFilters subroutine is run.

How to format Excel Tables with VBA ListObjects - Step 8b

It is how you format Excel tables with VBA ListObjects.

Examples

Go through some interesting examples to see how VBA ListObjects are being used in Excel.

Example #1

When you click on any cell inside a table, and you have multiple tables, you can get the name of the table by checking the ActiveCell’s object name by following the steps below.

Consider an example table:

Example 1
  • Step 1: Define a sub-procedure to find the table name the ActiveCell is in.
Example 1 - Step 1
  • Step 2: Declare a string variable to store the name of the ListObject.
Example 1 - Step 2
Example 1 - Step 3
  • Step 4: Using an If-condition, check if the string variable is not an empty string.
Example 1 - Step 4

If it isn’t empty, print the name of the ListObject in a MessageBox.

  • Step 5: Declare an Else condition in case there is no table where your ActiveCell is.
Example 1 - Step 5

Code:

Sub SelectedCellInTable()
Dim Test As String
On Error Resume Next
Test = ActiveCell.ListObject.name
On Error GoTo 0
If Test <> “” Then
MsgBox “Cell is part of the table named: ” & Test
Else
MsgBox “Cell is not part of any table”
End If
End Sub

  • Step 6: Run the sub-procedure and see the results.
Example 1 - Step 6

Your cursor is currently in the table “Table1.”

Example #2

Consider a table where you need to sort its numerical values in descending order. VBA ListObjects can be used to store the table and then sort using the functions available in the VBA ListObjects.

Example 2
  • Step 1: Name the subroutine which will sort a given table in either ascending or descending order.
Example 2 - Step 1
  • Step 2: Using VBA constants define the order of sorting and store it in an integer variable. Here, the table will be sorted in descending order.
Example 2 - Step 2
  • Step 3: Define a ListObject variable to store the table to be sorted.
Example 2 - Step 3
  • Step 4: If there are any sortings done earlier, remove them and bring them back to the default state. If it is not done, it may result in unexpected outputs.
Example 2 - Step 4
  • Step 5: Using the Sort.Sortfields function in ListObject, sort the second column with numerical values in descending order.
Example 2 - Step 5

Using the Add2 function, the rows in the table are sorted according to the “Key” component. In that, using the ListColumns function, select column 2 and sort it based on the sort order defined earlier.

  • Step 6: Apply the sorting function.
Example 2 - Step 6

Code:

Sub SortTable()
Dim SortOrder As Integer
SortOrder = xlDescending ‘(or xlAscending)
Dim tb2 As ListObject
Set tb2 = ActiveSheet.ListObjects(“Table7”)
‘Clear Any Prior Sorting
tb2.Sort.SortFields.Clear
tb2.Sort.SortFields.Add2 _
Key:=tb2.ListColumns(2).Range, _
Order:=SortOrder
tb2.Sort.Apply
End Sub

  • Step 7: Run the above subroutine and then view the table to see the results.
Example 2 - Step 7

With that, you’ve successfully sorted the table in descending order.

Example #3

Suppose you want to find the location of a value in the given table. If you type in the value to be searched, it will return the row number of the table it is in. This can be done using VBA ListObjects.

Example 3
  • Step 1: Name the subroutine to search for values in the table given above.
Example 3 - Step 1
Example 3 - Step 2

The Application.InputBox function doesn’t change pages to the Excel Workbook from the VBA Editor as the normal InputBox function does. The title of the InputBox is defined after the query to be asked. 9985650255

  • Step 3: Define the table with a ListObject. It is the table where the value will be searched for.
Example 3 - Step 3
 Example 3 - Step 4
  • Step 5: Search for the lookup value in the table. In this example, only the first column is considered for searching.
Example 3 - Step 5

Using the DataBodyRange attribute in the ListObject, find the value in the table by going through the whole table using the “xlWhole” constant in VBA. If found, store the address in the variable.

  • Step 6: Reset the Error numbers to 0.
Example 3 - Step 6
  • Step 7: Check if the cell is not empty. If so, print the table index where the value is found in a MessageBox.
Example 3 - Step 7
  • Step 8: Declare an Else condition to be executed in case the value isn’t found in the table.
 Example 3 - Step 8

Code:

Sub LookupTableValue()
Dim LookupValue As String
LookupValue = Application.InputBox(“Enter value in table”, “Search Table”)
Dim tbl As ListObject
Set tbl = ActiveWorkbook.Sheets(“Sheet4”).ListObjects(“Table4”)
On Error Resume Next
Dim FoundCell As Range
Set FoundCell = tbl.DataBodyRange.Columns(1).Find(LookupValue, LookAt:=xlWhole)
On Error GoTo 0
If Not FoundCell Is Nothing Then
MsgBox “Found in table row: ” & _
tbl.ListRows(FoundCell.Row – tbl.HeaderRowRange.Row).Index
Else
MsgBox “Value not found”
End If
End Sub

  • Step 9: Run the subroutine to search for the ID number in the table.
VBA ListObjects in Excel - Example 3 - Step 9a
VBA ListObjects in Excel - Example 3 - Step 9b

You’ve successfully created a subroutine to search for values in the table.

Important Things To Note

  • Leverage structured references when working with columns and data within ListObjects to enhance code readibility.
  • Before performing operations on a ListObject, check if it exists on the specified sheet.
  • When resizing tables, ensure that the new range maintains the table’s structure.
  • If your table is linked to external data, don’t forget to refresh it after the data source changes.
  • When resizing tables, avoid specifying ranges that disrupt the table’s structure, such as changing the number of columns inconsistently.

Frequently Asked Questions (FAQs)

1. Can I dynamically resize a ListObject in VBA?

Yes, you can dynamically resize a ListObject in VBA using the Resize method by specifying a new range.

2. How can I filter data in a ListObject using VBA?

Use the VBA ListObjects AutoFilter method on the ListObject to filter data based on specific criteria. Specify the column index and criteria for filtering as shown in the example below.

Excel VBA ListObjects - FAQ 2

3. Is it possible to add calculated columns to a ListObject using VBA?

Yes, it is possible to add calculated columns in Excel VBA using the VBA ListObjects.Add method. Let us look at the brief example below. Consider the table.

Excel VBA ListObjects - FAQ 3

To find the sum of the columns “Sales” and “Cost” you can add a new column to do so.

FAQ 3 - 1

Using the Excel “SUM” function, you can add a new column and do so.

FAQ 3 - 2

4. How do I delete a ListObject in VBA?

To delete a ListObject in VBA, use the Delete method on the ListObject.

Excel VBA ListObjects - FAQ 4

Download Template

This article must be helpful to understand the VBA ListObjects, with its syntax and examples. You can download the template here to use it instantly.

This has been a guide to VBA ListObjects. Here we learn how to create table format & format them using VBA coding, with examples & points to remember. You can learn more from the following articles –

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *