What is list object in excel vba

What are ListObjects in VBA?

In a Table, normally, what we see is a data set. Still, in VBA terminology, there are many more such as there is the range of the total data list range. The column is known as the list column, the row as the list row, and so on. To access these properties, we have an inbuilt function known as ListObjects, used with the worksheet function.

VBA ListObject is a way of referring to the Excel tables while writing the VBA code. Using VBA LISTOBJECTS, we can create and delete tables and play around with Excel Tables in VBA code. However, Excel Tables are tricky for beginners, and even to an extent, intermediate-level users find it difficult to work with Tables. Since this article talks about referencing excel tablesIn excel, tables are a range with data in rows and columns, and they expand when new data is inserted in the range in any new row or column in the table. To use a table, click on the table and select the data range.read more in VBA coding, you should have good knowledge about Tables in Excel.

When the data converts to tables, we may no longer work with a range of cells. Rather, we need to work with table ranges. So, this article will show you how to work with Excel Tables to write VBA codesVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more efficiently.

Table of contents
  • What are ListObjects in VBA?
    • Create Table Format Using ListObjects in Excel VBA
    • Formatting Excel Tables with VBA ListObjects
    • Things to Remember
    • Recommended Articles

VBA-ListObjects

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA ListObjects (wallstreetmojo.com)

Create Table Format Using ListObjects in Excel VBA

For example, look at the below Excel data.

List Object Excel Data

Using the VBA ListObject code, we will create a table format for this data.

You can download this VBA ListObjects Excel Template here – VBA ListObjects Excel Template

  • For this data, first, we need to find the last used row and column, so define two variables to find this.

Code:

Sub List_Objects_Example1()

    Dim LR As Long
    Dim LC As Long

End Sub

VBA List Object Example 1.2

  • To find the last used row and column use the below code.

Code:

LR = Cells(Rows.Count, 1).End(xlUp).Row
LC = Cells(1, Columns.Count).End(xlToLeft).Column

VBA List Object Example 1.3

  • Now define one more variable to hold the reference of the data.

Code:

Dim Rng As Range

VBA List Object Example 1.4

  • Now set the reference to this variable by using the below code.

Code:

Set Rng = Cells(1, 1).Resize(LR, LC)

VBA List Object Example 1.5

We need to use the VBA “ListObject.Add” method to create a table; below is the same syntax.

ListObject.Add (Source, XlListObjectHasHeaders, Destination, TableStyleName)

Source: TThis is nothing for which range of cells we are inserting the table. So we can supply two arguments here, i.e., “xlSrcRange” and “xlSrcExternal.”

XlListObjectHasHeaders: If the table inserting data has headers or not. If yes, we can provide “xlYes.” If not, we can provide “xlNo.”

Destination: This is nothing but our data range.

Table Style: We can provide styles if you want to apply any table style.

  • Now in the active sheet, we are creating the table, so the below code would create a table for us.

Code:

Dim Ws As Worksheet
Set Ws = ActiveSheet

Ws.ListObjects.Add xlSrcRange, xllistobjecthasheaders:=xlYes, Destination:=Rng

VBA List Object Example 1.6

  • After this, we need to give a name to this table.

Code:

Ws.ListObjects(1).name = "EmpTable"

VBA List Object Example 1.7

  • Below is the full code for your reference.

Code:

Sub List_Objects_Example1()

    Dim LR As Long
    Dim LC As Long

    LR = Cells(Rows.Count, 1).End(xlUp).Row
    LC = Cells(1, Columns.Count).End(xlToLeft).Column

    Dim Rng As Range
    Set Rng = Cells(1, 1).Resize(LR, LC)

    Dim Ws As Worksheet
    Set Ws = ActiveSheet

    Ws.ListObjects.Add xlSrcRange, xllistobjecthasheaders:=xlYes, Destination:=Rng
    Ws.ListObjects(1).name = "EmpTable"

End Sub

Let us run the code and see the magic.

VBA List Object Example 1.8

It has created the table to the mentioned data and given the table name “EmpTable.”

Formatting Excel Tables with VBA ListObjects

Once we create the Excel table, we can work with tables using the VBA ListObject collection.

  • First, define the variable as “ListObject.”

Code:

Sub List_Objects_Example2()

    Dim MyTable As ListObject

End Sub

VBA List Object Example 2.1

  • Now, set the reference to this variable by using the table name.

Code:

Sub List_Objects_Example2()

    Dim MyTable As ListObject
    Set MyTable = ActiveSheet.ListObjects("EmpTable")

End Sub

Set Reference

Now, the variable “MyTable” holds the reference for the table “EmpTable.”

  • Enter the variable name and put a dot to see the properties and methods of the VBA ListObject.

List Object Properties

For example, if we want to select the entire table, then we need to use the “Range” object, and under this, we need to use the “Select” method.

Code:

MyTable.Range.Select

List Object to Select Entire Table

It would select the entire data table, including the heading.

  • If you want to select only the table contents without headers, we need to use “DataBodyRange.”

Code:

MyTable.DataBodyRange.Select

To Select Table Content

Like this, we can play around with tables.

  • Below is the list of activity codes for your reference.

Code:

Sub List_Objects_Example2()

    Dim MyTable As ListObject
    Set MyTable = ActiveSheet.ListObjects("EmpTable")

    MyTable.DataBodyRange.Select
    'To Select data range without headers

    MyTable.Range.Select
    'To Select data range with headers

    MyTable.HeaderRowRange.Select
    'To Select table header rows

    MyTable.ListColumns(2).Range.Select
    'To select column 2 including header

    MyTable.ListColumns(2).DataBodyRange.Select
    'To select column 2 without header

End Sub

Like this, we can use the “ListObject” collection to play around with Excel tables.

Things to Remember

  • VBA ListObject is the collection of objects to reference excel tables.
  • To access the ListObject collection, we need to specify what worksheet we are referring to.

Recommended Articles

This article has been a guide to VBA ListObject. Here, we discuss how to use the VBA ListObject.Add method to create a table in Excel using examples downloadable Excel sheet. You can learn more from the following VBA articles: –

  • VBA Find Next
  • VBA Object Required
  • CreateObject in VBA
  • GetObject in VBA

The VBA Guide To ListObject Excel Tables

All About The Tables

For a data analyst, Excel Tables are a necessity!  They are the most efficient way to organize your raw data and refer to data that contracts or expands on a regular basis.  Likewise, Excel tables can be extremely useful in combination with VBA.  

I personally use data tables as a way to store user settings without having to modify any VBA code. You can see examples of this in my Exporter Template where I use tables to store worksheet names and email addresses.  

In this article, I wanted to bring all the common ways of referencing table data with VBA into one place.  Hopefully, this will serve as a guide you can come back to again and again so you can easily and efficiently incorporate tables into your VBA macro coding. Enjoy!

Section Quick Links

  • Excel Tables Overview

  • Selecting Areas Of A Table With VBA

  • Inserting Rows and Columns Into The Table

  • Deleting Parts Of A Table

  • Deleting/Clearing The Data In A Table

  • Loop Through Each Table Column Or Row

  • Looking Up Values Within A Table

  • Apply A Sort Order To A Table Column

  • Reading Table Data Into An Array Variable

  • Resizing A Table

  • Change All Table Column’s Total Row Calculations

  • Getting To The ActiveTable

  • Additional Articles

Excel Tables Overview

What Is A Table?

A Table is simply a structured range where you can refer to different sections that are automatically mapped out (such as the Header Row or the column below the header «Amount»). Tables are an amazing feature that Microsoft added into Excel because they not only structure your data, but they also expand with your data as it grows. And if there is one thing you should know about creating a spreadsheet, it would be that making it as DYNAMIC as possible is always a good thing!

You can quickly create a Table by highlighting a range (with proper headings) and using the keyboard shortcut Ctrl + t. You can also navigate to the Insert tab and select the Table button within the Tables group.

The Parts of A Table

The below infographic will help you visualize the different parts of a Table object through the lens of the VBA coding language.

These parts of a ListObject Table include:

  • Range

  • HeaderRowRange

  • DataBodyRange

  • ListRows

  • ListColumns

  • TotalsRowRange

Parts of VBA ListObject Table

How Do I Find Existing Tables?

Tables can be a little tricky to find if you are not familiar working with them because they can blend in very well with the spreadsheet depending on the formatting that has been applied.

Let’s look at 4 different ways you can determine if you are working with cells in a Table Object.

1. The Table Design Tab Appears

If you click within a cell that is part of an Excel Table, you will immediately see the Table Design tab appear in the Ribbon. This is a contextual tab, which means it only appears when a specific object is selected on your spreadsheet (a similar tab appears when Pivot Tables or Shapes are selected on a spreadsheet).

This is a very quick tell-tail sign that the cell you are working on is part of a Table Object.

2. The Blue Corner Indicator

There is a small little indicator at the bottom right cell of a Table range to indicate there is a table. As you can see in the image below, this indicator can be very simple to find, but also can be easily missed due to its small size!

Excel Table Corner Indicator

3. Use Excel’s Name Manager

Another great way to find a table (and its name) is to go into the Name Manager. You can get to the name manager by navigating to the Formulas tab and clicking the Name Manager button inside the Defined Names group.

By using the Filter menu in the right-hand corner of the Name Manager, you can narrow down your name list to just the Tables within the Workbook. The Name Manager will show you exactly where the tables are within the spreadsheet and also what the Table names are.

Find Table Information With Name Manager

4. VBA Code To Check If Cell Is In A ListObject Table

There may be instances when you need to determine if a certain cell resides within a ListObject (Table). The below VBA code shows you how you can perform a test to see if the ActiveCell (selected cell) is part of any Excel Table on the spreadsheet.

Sub IsActiveCellInTable()
‘PURPOSE: Determine if the current selected cell is part of an Excel Table
‘SOURCE: www.TheSpreadsheetGuru.com

Dim TestForTable As String

‘Test To See If Cell Is Within A Table
  On Error Resume Next
  TestForTable = ActiveCell.ListObject.Name
  On Error GoTo 0

‘Determine Results of Test
  If TestForTable <> «» Then
    ‘ActiveCell is within a ListObject Table
      MsgBox «Cell is part of the table named: » & TestForTable
  Else
    ‘ActiveCell is NOT within a ListObject Table
      MsgBox «Cell is not part of any table»
  End If

End Sub

This is a great validation test if you are creating code that allows the user to manipulate an excel table. I’ve used this many times to create buttons that allow users to insert or delete specific rows within a table based on where they select on a password protected sheet.

Selecting Areas of a Table with VBA

Select VBA Coding
Entire Table ActiveSheet.ListObjects(«Table1»).Range.Select
Table Header Row ActiveSheet.ListObjects(«Table1»).HeaderRowRange.Select
Table Data ActiveSheet.ListObjects(«Table1»).DataBodyRange.Select
Third Column ActiveSheet.ListObjects(«Table1»).ListColumns(3).Range.Select
Third Column (Data Only) ActiveSheet.ListObjects(«Table1»).ListColumns(3).DataBodyRange.Select
Select Row 4 of Table Data ActiveSheet.ListObjects(«Table1»).ListRows(4).Range.Select
Select 3rd Heading ActiveSheet.ListObjects(«Table1»).HeaderRowRange(3).Select
Select Data point in Row 3, Column 2 ActiveSheet.ListObjects(«Table1»).DataBodyRange(3, 2).Select
Subtotals ActiveSheet.ListObjects(«Table1»).TotalsRowRange.Select

Inserting Rows and Columns into the Table

Select VBA Coding
Insert A New Column 4 ActiveSheet.ListObjects(«Table1»).ListColumns.Add Position:=4
Insert Column at End of Table ActiveSheet.ListObjects(«Table1»).ListColumns.Add
Insert Row Above Row 5 ActiveSheet.ListObjects(«Table1»).ListRows.Add (5)
Add Row To Bottom of Table ActiveSheet.ListObjects(«Table1»).ListRows.Add AlwaysInsert:= True
Add Totals Row ActiveSheet.ListObjects(«Table1»).ShowTotals = True

Deleting Various Parts Of A Table

Sub RemovePartsOfTable()

Dim tbl As ListObject

Set tbl = ActiveSheet.ListObjects(«Table1»)

‘Remove 3rd Column
  tbl.ListColumns(3).Delete

‘Remove 4th DataBody Row
  tbl.ListRows(4).Delete

‘Remove 3rd through 5th DataBody Rows
  tbl.Range.Rows(«3:5»).Delete

‘Remove Totals Row
  tbl.TotalsRowRange.Delete

End Sub

Deleting/Clearing The Data In A Table

Delete all data rows from a table (except the first row)

Sub ResetTable()

Dim tbl As ListObject

Set tbl = ActiveSheet.ListObjects(«Table1»)

‘Delete all table rows except first row
  With tbl.DataBodyRange
    If .Rows.Count > 1 Then
      .Offset(1, 0).Resize(.Rows.Count — 1, .Columns.Count).Rows.Delete
    End If
  End With

‘Clear out data from first table row
  tbl.DataBodyRange.Rows(1).ClearContents

End Sub

If you have formulas in your table, you may want to keep those intact. The following modification will just remove constant values from the remaining first row in the Table Object.

Sub ResetTable()

Dim tbl As ListObject

Set tbl = ActiveSheet.ListObjects(«Table1»)

‘Delete all table rows except first row
  With tbl.DataBodyRange
    If .Rows.Count > 1 Then
      .Offset(1, 0).Resize(.Rows.Count — 1, .Columns.Count).Rows.Delete
    End If
  End With

‘Clear out data from first table row (retaining formulas)
  tbl.DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents

End Sub

Loop Through Each Table Column Or Row

Sub LoopingThroughTable()

Dim tbl As ListObject
Dim x As Long

Set tbl = ActiveSheet.ListObjects(«Table1»)

‘Loop Through Each Column in Table
  For x = 1 To tbl.ListColumns.Count
    tbl.ListColumns(x).Range.ColumnWidth = 8
  Next x

‘Loop Through Every Row in Table
  For x = 1 To tbl.Range.Rows.Count
    tbl.Range.Rows(x).RowHeight = 20
  Next x

  ‘Loop Through Each DataBody Row in Table
  For x = 1 To tbl.ListRows.Count
    tbl.ListRows(x).Range.RowHeight = 15
  Next x

End Sub

Apply Sort To Column In A Table

You may find yourself needing to sort your Table data in either Ascending or Descending order. The following VBA code will show you how to sort a column in your ListObject Table in either order.

Sub SortTableColumn()
‘PUPOSE: Sort Table in Ascending/Descending Order
‘SOURCE: www.TheSpreadsheetGuru.com

Dim tbl As ListObject
Dim SortOrder As Integer

‘Choose Sort Order
  SortOrder = xlAscending ‘(or xlDescending)

‘Store Desired Excel Table to a variable
  Set tbl = ActiveSheet.ListObjects(«Table1»)

‘Clear Any Prior Sorting
  tbl.Sort.SortFields.Clear

    ‘Apply A Sort on Column 1 of Table
    tbl.Sort.SortFields.Add2 _
        Key:=tbl.ListColumns(1).Range, _
        SortOn:=xlSortOnValues, _
        Order:=SortOrder, _
        DataOption:=xlSortNormal

    ‘Sort Options (if you want to change from default)
  tbl.Sort.Header = xlYes
  tbl.Sort.MatchCase = False
  tbl.Sort.Orientation = xlTopToBottom
  tbl.Sort.SortMethod = xlPinYin

‘Apply the Sort to the Table
  tbl.Sort.Apply

End Sub

While the above VBA code has all the potential options written out for you to tweak, most of the time you will not need to stray away from the default sorting options.

Below is the same code, but with all the options you likely don’t need to change from their default setting value removed.

Sub SortTableColumn_Simple()
‘PUPOSE: Sort Table in Ascending/Descending Order
‘SOURCE: www.TheSpreadsheetGuru.com

Dim tbl As ListObject
Dim SortOrder As Integer

‘Choose Sort Order
  SortOrder = xlDescending  ‘(or xlAscending)

‘Store Desired Excel Table to a variable
  Set tbl = ActiveSheet.ListObjects(«Table1»)

‘Clear Any Prior Sorting
  tbl.Sort.SortFields.Clear

‘Apply A Sort on Column 1 of Table
    tbl.Sort.SortFields.Add2 _
        Key:=tbl.ListColumns(1).Range, _
        Order:=SortOrder

‘Apply the Sort to the Table
  tbl.Sort.Apply

End Sub

Looking Up Values Within A Table

If you are storing values inside a Table, there may be scenarios where you wish to look up or find a value. There are many different lookup scenarios one might have, but for simplicity, I will provide a generic example. The following code looks to find an ID string within a specific table’s first column and returns that ID’s table row number. Hopefully, you can use the logic within this example and apply it to your specific needs.

Sub LookupTableValue()

Dim tbl As ListObject
Dim FoundCell As Range
Dim LookupValue As String

‘Lookup Value
  LookupValue = «ID-123»

‘Store Table Object to a variable
  Set tbl = ActiveSheet.ListObjects(«Table1»)

‘Attempt to find value in Table’s first Column
  On Error Resume Next
  Set FoundCell = tbl.DataBodyRange.Columns(1).Find(LookupValue, LookAt:=xlWhole)
  On Error GoTo 0

‘Return Table Row number if value is found
  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

Store Table Data In An Array Variable

Pulling in data from tables is a great tactic to incorporate in your VBA coding.  Tables are ideal because they:

  • Are always structured the same

  • Can be moved anywhere on the spreadsheet without affecting your code

  • Automatically adjust their range size

One example of using Tables as a data source in a macro is shown in one of my Code Vault snippets which allows you to filter your data based on the words in a specified table.  There are tons of different ways you can use tables to store settings and preferences dynamically for your macros. The below code shows you how to load in data from a single column and a multi-column table.

Single Column Table

Sub SingleColumnTable_To_Array()

Dim myTable As ListObject
Dim myArray As Variant
Dim TempArray As Variant
Dim x As Long

‘Set path for Table variable
  Set myTable = ActiveSheet.ListObjects(«Table1»)

‘Create Array List from Table
  TempArray = myTable.DataBodyRange

  ‘Convert from vertical to horizontal array list
  myArray = Application.Transpose(TempArray)

‘Loop through each item in the Table Array (displayed in Immediate Window [ctrl + g])
  For x = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(x)
  Next x

  End Sub

Multiple Column Table

Sub MultiColumnTable_To_Array()

Dim myTable As ListObject
Dim myArray As Variant
Dim x As Long

‘Set path for Table variable
  Set myTable = ActiveSheet.ListObjects(«Table1»)

‘Create Array List from Table
  myArray = myTable.DataBodyRange

‘Loop through each item in Third Column of Table (displayed in Immediate Window [ctrl + g])
  For x = LBound(myArray) To UBound(myArray)
    Debug.Print myArray(x, 3)
  Next x

  End Sub

Resizing A Table

If needed, you can resize a table’s dimensions by declaring a new range area for the Excel table to shrink or expand.  Below are a couple of examples showing how you can perform this sort of size adjustment.

(A special thanks to Peter Bartholomew for requesting this on LinkedIn)

Sub ResizeTable()

Dim rng As Range
Dim tbl As ListObject

‘Resize Table to 7 rows and 5 columns
  Set rng = Range(«Table1[#All]»).Resize(7, 5)

    ActiveSheet.ListObjects(«Table1»).Resize rng

    ‘Expand Table size by 10 rows
  Set tbl = ActiveSheet.ListObjects(«Table1»)

    Set rng = Range(tbl.Name & «[#All]»).Resize(tbl.Range.Rows.Count + 10, tbl.Range.Columns.Count)

    tbl.Resize rng

End Sub

Change All Table Total Row Calculations

Sub ChangeAllColumnTotals()

Dim tbl As ListObject
Dim CalcType As Integer
Dim x As Long

Set tbl = ActiveSheet.ListObjects(«Table1»)

‘What calculation should the Totals Row Have?
  CalcType = 1 ‘or: xlTotalsCalculationSum

‘Loop Through All Table Columns
  For x = 1 To tbl.ListColumns.Count
    tbl.ListColumns(x).TotalsCalculation = CalcType
  Next x

‘___________________________________________
‘Members of xlTotalsCalculation
    ‘Enum       Calculation
    ‘ 0           None
    ‘ 1           Sum
    ‘ 2           Average
    ‘ 3           Count
    ‘ 4           Count Numbers
    ‘ 5           Min
    ‘ 6           Max
    ‘ 7           Std Deviation
    ‘ 8           Var
    ‘ 9           Custom
‘___________________________________________

End Sub

Getting the ActiveTable

There may be instances where you want to make a personal macro that formats your selected table in a certain way or adds certain calculation columns.  Since the Excel developers didn’t create an ActiveTable command in their VBA language, you have no straightforward way of manipulating a user-selected table.  But with a little creativity, you can make your own ActiveTable ListObject variable and do whatever you want with the selected table!

Sub DetermineActiveTable()

Dim SelectedCell As Range
Dim TableName As String
Dim ActiveTable As ListObject

Set SelectedCell = ActiveCell

‘Determine if ActiveCell is inside a Table
  On Error GoTo NoTableSelected
    TableName = SelectedCell.ListObject.Name
    Set ActiveTable = ActiveSheet.ListObjects(TableName)
  On Error GoTo 0

‘Do something with your table variable (ie Add a row to the bottom of the ActiveTable)
  ActiveTable.ListRows.Add AlwaysInsert:=True

  Exit Sub

‘Error Handling
NoTableSelected:
  MsgBox «There is no Table currently selected!», vbCritical

End Sub

Visual Learner? Download My Example Workbook

Screenshot from one of the tabs in the downloadable file

After many requests, I put together a fun little interactive workbook that will show you how a bunch of the code described in this article actually works on a spreadsheet.  It also serves as a good reference that you can save to your computer so you don’t have to keep googling about Excel Tables whenever something slips your mind.  

Download Example Excel File

If you would like to get a copy of the Excel file I used throughout this article, feel free to directly download the spreadsheet by clicking the download button below.

Anything Else About Tables I Missed?

Did you come to this page trying to find out how to do something with VBA and Excel tables and it wasn’t covered? If that is the case, let me know what you were looking for in the comment section below.  If it makes sense to add it to this guide and will definitely add it to the content.  I look forward to reading your thoughts and/or recommendations!

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you some value today and hope to see you back here soon! — Chris

In this Article

  • Using a VBA ArrayList
    • Distributing Your Excel Application Containing an Array List
    • Scope of an Array List Object
    • Populating and Reading from Your Array List
    • Editing and Changing Items in an Array List
    • Adding an Array of Values to an Array List
    • Reading / Retrieving a Range of Items from an Array List
    • Searching for Items Within an Array List
    • Insert and Remove Items
    • Sorting an Array List
    • Cloning an Array List
    • Copying a List Array into a Conventional VBA Array Object
    • Copying a List Array into a Worksheet Range
    • Empty All Items from an Array List
    • Array List Methods Summary for Excel VBA

Using a VBA ArrayList

An ArrayList is a VBA object that can be used to store values. It is similar to a Collection object, but it has far greater flexibility from a programming point of view. Let’s discuss some difference between ArrayLists and Collections and Arrays.

  • The Collection object only has two methods (Add, Remove) and two properties (Count, Item) whereas an Array List has many more.
  • The Collection object is read only. Once values have been added, the indexed value cannot be changed, whereas on an Array List, editing is possible.
  • The ArrayList object expands and contracts in size according to how many items that it contains.  It does not need to be dimensioned before use like an Array.
  • The ArrayList is one dimensional (same as the Collection object) and the default data type is Variant, which means that it will accept any type of data, whether it be numeric, text, or date.

In many ways the Array List addresses a number of shortcomings of the Collection object. It is certainly far more flexible in what it can do.

The Array List object is not part of the standard VBA library. You can use it in your Excel VBA code by using late or early binding.

Sub LateBindingExample()
Dim MyList As Object
Set MyList = CreateObject("System.Collections.ArrayList")
End Sub
Sub EarlyBindingExample()
Dim MyList As New ArrayList
End Sub

In order to use the early binding example, you must first enter a reference in VBA to the file ‘mscorlib.tlb’

You do this by selecting ‘Tools | References ‘ from the Visual Basic Editor (VBE) window. A pop-up window will appear with all available references. Scroll down to ‘mscorlib.dll’ and tick the box next to it. Click OK and that library is now part of your project:

Pic 01

One of the big drawbacks of an Array List object is that it does not have ‘Intellisense’. Normally, where you are using an object in VBA such as a range, you will see a pop-up list of all the available properties and methods.  You do not get this with an Array List object, and it sometimes needs careful checking to make sure that you have spelt the method or property correctly.

Also, if you press F2 in the VBE window, and search on ‘arraylist’, nothing will be displayed, which is not very helpful to a developer.

Your code will run considerably faster with early binding, because it is all compiled up front. With late binding, the object has to be compiled as the code runs

Distributing Your Excel Application Containing an Array List

As already pointed out, the ArrayList object is not part of Excel VBA. This means that any of your colleagues that you distribute the application to must have access to the file ‘mscorlib.tlb’

This file is normally located in:

C:WindowsMicrosoft.NETFrameworkv4.0.30319

It could be worth writing some code (using the Dir method) to check that this file exists when a user loads the application so that they experience a ‘soft landing’ if not found. If it is not present, and the code runs then errors will occur.

Also, the user must have the correct .Net Framework version installed. Even if the user has a later version, V3.5 must be installed otherwise your application will not work

Scope of an Array List Object

In terms of scope, the Array List object is only available whilst the workbook is open. It does not get saved when the workbook is saved. If the workbook is re-opened then the Array List object needs to be re-created using VBA code.

If you want your Array List to be available to all the code in your code module, then you need to declare the Array List object in the Declare section at the very top of the module window

This will ensure that all your code within that module can access the Array List.  If you want any module within your workbook to access the Array List object, then define it as a global object.

Global MyCollection As New ArrayList

Populating and Reading from Your Array List

The most basic action that you want to take is to create an array list, put some data into it and then prove that the data can be read.  All the code examples in this article assume that you are using early binding, and have added ‘mscorlib.tlb’ to the VBA references, as described above.

Sub ArrayListExample()
'Create new array list object
Dim MyList As New ArrayList

'Add items to list
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"

'Iterate through array list to prove values
For N = 0 To MyList.Count - 1
    MsgBox MyList(N)
Next N

End Sub

This example creates a new ArrayList object, populates it with 3 items, and the iterates through the list displaying each item.

Note that the ArrayList index starts at 0, not 1, so you need to subtract 1 from the Count value

You can also use a ‘For…Each’ loop to read the values:

Sub ArrayListExample()
'Create new array list object
Dim MyList As New ArrayList

'Add items to list
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"

'Iterate through array list to prove values
For Each I In MyList
    MsgBox I
Next I

End Sub

Editing and Changing Items in an Array List

A major advantage of an Array List over a Collection is that the items in the list can be edited and changed within your code. The Collection object is read only whereas the Array List object is read / write.

Sub ArrayListExample()
'Create new array list object
Dim MyList As New ArrayList

'Add items to list
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"

'Change item 1 from ‘Item2’ to ‘Changed’
MyList(1) = "Changed"

'Iterate through array list to prove change worked
For Each I In MyList
    'Display item name
    MsgBox I
Next I

End Sub

In this example, the second item, ‘Item2’ is altered to the value ‘Changed’ (remember that the index starts at 0). When the iteration is run at the end of the code, the new value will be displayed.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Adding an Array of Values to an Array List

You can enter values into your Array List by using an array containing a list of these values or references to cell values on a worksheet

Sub AddArrayExample()
'Create Array list object
Dim MyList As New ArrayList

'iterate through array values adding them to the array list
For Each v In Array("A1", "A2", "A3")
    'Add each array value to list		
    MyList.Add v
Next

'iterate through array values with worksheet references adding them to the array list
For Each v In Array(Range("A5").Value, Range("A6").Value)
    MyList.Add v
Next

'Iterate through array list to prove values
For N = 0 To MyList.Count – 1
   'Display list item
    MsgBox MyList.Item(N)
Next N

End Sub

Reading / Retrieving a Range of Items from an Array List

By using the GetRange method on an Array List, you can specify a rage of consecutive items to be retrieved. The two parameters required are the starting index position and the number of items to be retrieved. The code populates a second Array List object with the sub set of items which can then be read separately.

Sub ReadRangeExample()
'Define objects
Dim MyList As New ArrayList, MyList1 As Object

'Add items to ‘MyList’ object
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
MyList.Add "Item6"
MyList.Add "Item4"
MyList.Add "Item7"

'Capture 4 items in ‘MyList’ starting at index position 2
Set MyList1 = MyList.GetRange(2, 4)

'Iterate through the object ‘MyList1’ to display the sub set of items
For Each I In MyList1
   'Display item name
    MsgBox I
Next I

End Sub

Searching for Items Within an Array List

You can test whether a named item is in your list by using the ‘Contains’ method. This will return True or False

MsgBox MyList.Contains("Item2")

You can also find the actual index position by using the ‘IndexOf’ method. You need to specify the start index for the search (usually 0).  The return value is the index of the first instance of the found item.  You can then use a loop to change the starting point to the next index value to find further instances if there are several duplicate values.

If the value is not found then a value of -1 is returned

This example demonstrates using ‘Contains’, item not found, and looping through the array list to find the position of all duplicate items:

Sub SearchListExample()
'Define array list and variables
Dim MyList As New ArrayList, Sp As Integer, Pos As Integer

'Add new items including a duplicate
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
MyList.Add "Item1"

'Test for “Item2” being in list - returns True
MsgBox MyList.Contains("Item2")

'Get index of non-existent value – returns -1
MsgBox MyList.IndexOf("Item", 0)

'Set the start position for the search to zero
Sp = 0

'Iterate through list to get all positions of ‘Item1”
Do
     'Get the index position of the next ‘Item1’ based on the position in the variable ‘Sp’
    Pos = MyList.IndexOf("Item1", Sp)
   'If no further instances of ‘Item1’ are found then exit the loop
    If Pos = -1 Then Exit Do
   'Display the next instance found and the index position
    MsgBox MyList(Pos) & " at index " & Pos
   'Add 1 to the last found index value – this now becomes the new start position for the next search
    Sp = Pos + 1
Loop

End Sub

Note that the search text used is case sensitive and wild cards are not accepted.

VBA Programming | Code Generator does work for you!

Insert and Remove Items

If you do not wish to add your items onto the end of the list, you can insert them at a particular index position so that the new item is in the middle of the list. The index numbers will be automatically adjusted for the subsequent items.

Sub InsertExample()
'Define array list object
Dim MyList As New ArrayList

'Add items to array list
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
MyList.Add "Item1"

'Insert ‘Item6’ at index position 2
MyList.Insert 2, "Item6"

'Iterate through items in the array list to show new order and index position
For N = 0 To MyList.Count - 1
    MsgBox MyList(N) & " Index " & N
Next N

End Sub

In this example, ‘Item6’ is added into the list at index position 2, so the ‘item3’ which was at index position 2 now moves to index position 3.

An individual item can be removed by using the ‘Remove’ method.

MyList.Remove "Item"

Note that there is no error produced if the item name is not found. All the subsequent index numbers will be changed to suit the removal.

If you know the index position of the item you can use the ‘RemoveAt’ method e.g.

MyList.RemoveAt 2

Note that if the index position given is greater than the number of items in the array list, then an error will be returned.

You can remove a range of values from the list by using the ‘RemoveRange’ method.  The parameters are the starting index and then the number of items to remove e.g.

MyList.RemoveRange 3, 2

Note that you will get an error in your code if the number of items offset from the start value is greater than the number of items in the array list.

In both the ‘RemoveAt’ and ‘RemoveRange’ methods, some code would be advisable to check whether the index numbers specified are greater than the total number of items in the array list in order to trap any possible errors.  The ‘Count’ property will give the total number of items in the array list.

Sub RemoveExample()
'Define array list object
Dim MyList As New ArrayList
'Add items to array list
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
MyList.Add "Item1"
MyList.Add "Item4"
MyList.Add "Item5"
'Insert ‘Item6’ at index position 2
MyList.Insert 2, "Item6"
'Remove ‘Item2’
MyList.Remove "Item2"
'Remove ‘Item’ – this does not exist in the array list but does not error
MyList.Remove "Item"
'Remove the item at index position 2
MyList.RemoveAt 2
'Remove 2 consecutive items starting at index position 2
MyList.RemoveRange 3, 2
'Iterate through the array list to show what is left and what index position it is now in
For N = 0 To MyList.Count - 1
    MsgBox MyList(N) & " Index " & N
Next N
End Sub

Note that if you are using the ‘RemoveAt’ to remove an item at a specific position then as soon as that item is removed, all the subsequent index positions are altered. If you have multiple removals using the index position, then a good idea is to start with the highest index number and step backwards down to position zero so that you will always be removing the correct item. In this way you will not have the problem

Sorting an Array List

Another big advantage over a collection is that you can sort the items into ascending or descending order.

The Array List object is the only object in Excel VBA with a sorting method.  The sorting method is very fast and this can be an important consideration for using an Array List.

In the collection object, some ‘out of the box’ thinking was required to sort all the items, but with an array list, it is very simple.

The ‘Sort’ method sorts in ascending order, and the ‘Reverse’ method sorts in descending order.

Sub ArrayListExample()
'Create Array List object
Dim MyList As New ArrayList
'Add items in a non-sorted order
MyList.Add "Item1"
MyList.Add "Item3"
MyList.Add "Item2"
'Sort the items into ascending order
MyList.Sort
'Iterate through the items to show ascending order
For Each I In MyList
    'Display item name
    MsgBox I
Next I
'Sort the items into descending order
MyList.Reverse
'Iterate through the items to show descending order
For Each I In MyList
    'Display item name
    MsgBox I
Next I
End Sub

Cloning an Array List

An array list has the facility to create a clone or copy of itself.  This is useful if a user makes changes to the items using a front end and your VBA code, but you need to keep a copy of the items in their original state as a backup.

This could provide the user with an ‘Undo’ feature. They may have made the changes, and wish to revert back to the original list.

Sub CloneExample()
'Define two objects – array list and an object
Dim MyList As New ArrayList, MyList1 As Object
'Populate first object with items
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
'Copy Mylist to MyList1
Set MyList1 = MyList.Clone
'Iterate through MyList1 to prove cloning
For Each I In MyList1
    'Display item name
    MsgBox I
Next I
End Sub

‘MyList1’ now contains all the items from ‘MyList’ in the same order

Copying a List Array into a Conventional VBA Array Object

You can use a simple method to copy the array list into a normal VBA array:

Sub ArrayExample()
'Create array list object and a standard array object
Dim MyList As New ArrayList, NewArray As Variant
'Populate array list with items
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
'Copy the array list to the new array
NewArray = MyList.ToArray
'Iterate through the new array – note that the array list count provides the maximum index
For N = 0 To MyList.Count – 1
    'Display item name
    MsgBox NewArray(N)
Next N
End Sub

Copying a List Array into a Worksheet Range

You can copy your array list to a specific worksheet and cell reference without the need to iterate through the array list. You need only specify the first cell reference

Sub RangeExample()
'Create new array list object
Dim MyList As New ArrayList
'Add items to list
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
'Clear the target sheet
Sheets("Sheet1").UsedRange.Clear
'Copy items across a row
Sheets("Sheet1").Range("A1").Resize(1, MyList.Count).Value = MyList.toArray
'Copy items down a column
Sheets("Sheet1").Range("A5").Resize(MyList.Count, 1).Value =  _
WorksheetFunction.Transpose(MyList.toArray)
End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Empty All Items from an Array List

There is a simple function (Clear) to clear the array list completely

Sub ClearListExample()
'Create array list object
Dim MyList As New ArrayList
'Add new items
MyList.Add "Item1"
MyList.Add "Item2"
MyList.Add "Item3"
'Show count of items
MsgBox MyList.Count
'Clear all items
MyList.Clear
'Show count of items to prove that clear has worked
MsgBox MyList.Count
End Sub

This example creates items in an array list and then clears the array list.  Message boxes prove before and after the number of items in the array list.

Array List Methods Summary for Excel VBA

Task Parameters Examples
Add / Edit item Value MyList.Add “Item1”
MyList(4)= “Item2”
Clone an Array List None Dim MyList As Object
Set MyList2 = MyList.Clone
Copy to Array None Dim MyArray As Variant
MyArray = MyList.ToArray
Copy to a worksheet range(row) None Sheets(“Sheet1”).Range(“A1”).Resize(1, MyList.Count).Value = MyList.ToArray
Copy to a worksheet  range(column) None Sheets(“Sheet1”).Range(“A3”).Resize(MyList.Count, 1).Value = WorksheetFunction.Transpose(MyList.ToArray)
Create “System.Collections.ArrayList” Dim MyList As Object
Set MyList = CreateObject(“System.Collections.ArrayList”)
Declare N/A Dim MyList As Object
Find / check if item exists Item to find MyList.Contains(“Item2”)
Find the position of an item in the ArrayList 1. Item to find. Dim IndexNo As Long
2. Position to start searching from.  IndexNo = MyList.IndexOf(“Item3”, 0)
IndexNo = MyList.IndexOf(“Item5”, 3)
Get number of items None MsgBox MyList.Count
Insert Item 1. Index – position to insert at. MyList.Insert 0, “Item5”
2 Value – object or value to insert. MyList.Insert 4, “Item7”
Read item Index – long integer MsgBox MyList.Item(0)
MsgBox MyList.Item(4)
Read item added last Index – long integer MsgBox MyList.Item(list.Count – 1)
Read item added first Index – long integer MsgBox MyList.Item(0)
Read all items(For Each) N/A Dim element As Variant
For Each element In MyList
   MsgBox element
Next element
Read all items(For) Index – long integer Dim i As Long
For i = 0 To MyList.Count – 1
   MsgBox i
Next i
Remove all Items None MyList.Clear
Remove item at position Index position where the item is MyList.RemoveAt 5
Remove item by name The item to remove from the ArrayList MyList.Remove “Item3”
Remove a range of Items 1. Index – starting postion. MyList.RemoveRange 4,3
2. Count – the number of items to remove.
Sort in Descending Order None MyList.Reverse
Sort in ascending order Non MyList.Sort

VBA ListObject Object in Excel. The ListObjects collection contains listobject objet. It represents a object on worksheet and most powerful feature. This object contains different methods and properties. In the following tutorial you learn methods, properties of listobject object. And also learn syntax of it.

We have different methods and properties for ListObject Object in Excel VBA.

The methods are Delete, ExportToVisio,Publish, Refresh, Resize, Unlink, and Unlist in Excel VBA.

VBA ListObject Object

The properties are Active, AlternativeText, Application, AutoFilter, Comment, Creator, DataBodyRange, DisplayName, DisplayRightToLeft, HeaderRowRange, InsertRowRange, ListColumns, ListRows, Name, Parent, QueryTable, Range, SharePointURL, ShowAutoFilter, ShowAutoFilterDropDown, ShowHeaders, ShowTableStyleColumnStripes, ShowTableStyleFirstColumn, ShowTableStyleLastColumn, ShowTableStyleRowStripes, ShowTotals, Slicers, Sort, SourceType, Summary, TableObject, TableStyle, TotalsRowRange, and XmlMap.

Let us see complete details about methods & properties and.

VBA ListObject Object Methods in VBA

Here are the listobject object methods in VBA. Let us see syntax each method.

Delete

Deletes the ListObject object and clears data on the Worksheet cells.

ListObject.Delete

ExportToVisio

Exports a ListObject object to Visio.

ListObject.ExportToVisio

Publish

Publishes the ListObject object to a server that is running Microsoft SharePoint Foundation.

ListObject.Publish (Target, LinkSource)

Where
Target is a required parameter. It contains array of strings variant type data.
LinkSource is a required parameter. It contains Boolean type data depending on the target.

Refresh

Retrieves the current data and schema for the list from the server that is running Microsoft SharePoint Foundation.

ListObject.Refresh

Resize

The Resize method allows a ListObject object to be resized over a new range. No cells are inserted or moved.

ListObject.Resize (Range)

Unlink

Removes the link to a Microsoft SharePoint Foundation site from a list and returns Nothing.

ListObject.Unlink

Unlist

Removes the list functionality from a ListObject object. After use, the range of cells that made up the the list will be a regular range of data.

ListObject.Unlist

VBA ListObject object Properties in VBA

Let us see the the listobject object properties in VBA. Let us see syntax of each property.

Active

Checks the active cell is inside the range of the ListObject object. It returns a Boolean value indicating whether a ListObject object on a worksheet is active or not. It allows to read only.

ListObject.Active

AlternativeText

This property returns or sets the descriptive text string for the specified table. It allows to read or write.

ListObject.AlternativeText

Application

It is a property and returns an Application object that represents the Microsoft Excel application.

ListObject.Application

AutoFilter

It filters a table using the AutoFilter feature. It allows to read only.

ListObject.AutoFilter

Comment

This property returns or sets the comment associated with the list object. It is to read or write and string type data.

ListObject.Comment

Creator

It returns a 32-bit integer. It represents the application in which this object was created. It allows to read only and Long type data.

ListObject.Creator

DataBodyRange

It returns a Range object that represents the range of values, excluding the header row, in a table. It allows to read only.

ListObject.DataBodyRange

DisplayName

This property returns or sets the display name for the specified ListObject object. It allows to read or write and string type data.

ListObject.DisplayName

DisplayRightToLeft

True if the specified ListObject is displayed from right to left instead of from left to right. False if the object is displayed from left to right. It allows to read only and Boolean type data.

ListObject.DisplayRightToLeft

HeaderRowRange

It returns a Range object that represents the range of the header row for a list. It allows to read only and contains range object.

ListObject.HeaderRowRange

InsertRowRange

This property returns a Range object representing the Insert row for the specified ListObject object. It allows to read only and contains range object.

ListObject.InsertRowRange

ListColumns

It returns a ListColumns collection that represents all the columns in a ListObject object. It allows to read only.

ListObject.ListColumns

ListRows

It returns a ListRows collection that represents all the columns in a ListObject object. It allows to read only.

ListObject.ListRows

Name

This property returns or sets a String value that represents the name of the ListObject object.

ListObject.Name

Parent

It returns the parent object for the specified object. It allows to read only.

ListObject.Parent

QueryTable

This property returns the QueryTable object that provides a link for the ListObject object to the list server. It allows to read only.

ListObject.QueryTable

Range

It returns a Range object that represents the range to which the specified list object in the list applies.

ListObject.Range

SharePointURL

Returns a String representing the URL of the SharePoint list for a given ListObject object. It allows to read only and string type data.

ListObject.SharePointURL

ShowAutoFilter

This property returns Boolean to indicate whether the AutoFilter will be displayed. It allows to read or write and conatins Boolean type data.

ListObject.ShowAutoFilter

ShowAutoFilterDropDown

It returns True when the AutoFilter drop-down for the ListObject object is displayed. It allows to read or write and conatins Boolean type data.

ListObject.ShowAutoFilterDropDown

ShowHeaders

It returns or sets if the header information should be displayed for the specified ListObject object. It allows to read or write and conatins Boolean type data.

ListObject.ShowHeaders

ShowTableStyleColumnStripes

This property returns or sets if the Column Stripes table style is used for the specified ListObject object. It allows to read or write and conatins Boolean type data.

ListObject.ShowTableStyleColumnStripes

ShowTableStyleFirstColumn

It returns or sets if the first column is formatted for the specified ListObject object. It allows to read or write and conatins Boolean type data.

ListObject.ShowTableStyleFirstColumn

ShowTableStyleLastColumn

It returns or sets if the last column is displayed for the specified ListObject object. It allows to read or write and conatins Boolean type data.

ListObject.ShowTableStyleLastColumn

ShowTableStyleRowStripes

This property returns or sets if the Row Stripes table style is used for the specified ListObject object. It allows to read or write and conatins Boolean type data.

ListObject.ShowTableStyleRowStripes

ShowTotals

It gets or sets a Boolean to indicate whether the Total row is visible.It allows to read or write and conatins Boolean type data.

ListObject.ShowTotals

Slicers

It returns a list of the table slicers associated with a ListObject. It allows to read.

ListObject.Slicers

Sort

It gets or sets the sort column or columns and sort order for the ListObject collection.

ListObject.Sort

SourceType

This property returns an XlListObjectSourceType value that represents the current source of the list.

ListObject.SourceType

Summary

It returns or sets the description associated with the alternative text string for the specified table. It allows to read or write.

ListObject.Summary

TableObject

This property returns a TableObject object. It allows to read only.

ListObject.TableObject

TableStyle

It gets or sets the table style for the specified ListObject object. It allows to read or write and contains variant type data.

ListObject.TableStyle

TotalsRowRange

This property returns a Range object representing the Total row, if any, from a specified ListObject object. It allows to read only.

ListObject.TotalsRowRange

XmlMap

It returns an XmlMap object that represents the schema map used for the specified table. It allows to read only.

ListObject.XmlMap

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel VBA Tables and ListObjects

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers Blog

The ListObjects property of the Worksheet object returns the ListObjects collection. The ListObjects collection contains all the list objects on a worksheet. The ListObject object is a member of the ListObjects collection. Each ListObject object represents a table (previously known as a list) in the worksheet.

An Excel table typically contains related data in a series of worksheet rows and columns that have been formatted as a table. By using the table features, you can then manage the data in the table rows and columns independently from the data in other rows and columns on the worksheet.

Here is how a table (list) looks like. It can be identified by a small blue arrow at the right-most bottom-most cell of the table.

Whenever you import data from a file (Excel / Text / XML / JSON) or from a database (SQL / Access), the imported data is always in the form of a table.

You can also convert the selected range in Excel to a table by using the Format as Table option. For that simply select your data range, in the home tab, go to “Format as Table” and select the desired formatting. You will asked to confirm the selected data range and whether your table has headers. Input the data and click on OK and a table will be created.

To convert a table back to normal range, use the convert to range option. For that, click anywhere on the table, the design tab will be visible. In the design tab, click on convert to range.

Now, that we know what is a table let us look at how to use VBA to modify these tables.

Example 1: Loop through all the tables (lists) in a worksheet

The code below creates a new ListObjects collection which represents all the tables in a worksheet and displays the name of each of the table in the collection. The code along with the comments is self-explanatory.

Sub excelLists()
    Dim dataSheet As Worksheet
    Dim tableList As ListObjects
    Dim table As ListObject

    Set dataSheet = Sheet1

    'create a new ListObjects collection which represents all the tables in Sheet1
    Set tableList = dataSheet.ListObjects

    'Loop through each table in the tableList ListObjects collection
    For Each table In tableList

        'Display the table name
        MsgBox table.Name

    Next table

End Sub

The name of the table can be seen in the design tab. Select any cell in the table and the design tab will be shown. The name of the selected table is seen in the left side of the tab. You can edit it from here. You can also see a list of all the tables in the workbook along with their names and ranges in the Name Manager (in the Formulas tab).

Example 2: Column operations on a table

In this example we will see few of the most common operations that you can perform on the table columns. Namely, looping through all the columns of a table and printing their names, inserting columns at the end or at a specified position, deleting a particular column and copying only the data from a particular column.

Sub ListCols()
    Dim dataSheet As Worksheet
    Dim table As ListObject
    Dim tblCols As ListColumns
    Dim tblCol As ListColumn
    Dim newCol As ListColumn

    Set dataSheet = Sheet1

    'Refer a table by it's name
    Set table = dataSheet.ListObjects("Table2")

    'Get all the columns of a table
    Set tblCols = table.ListColumns

    'Loop through all the columns of a table
    For Each tblCol In tblCols
        MsgBox tblCol.Name
    Next tblCol

    'Insert a column at the last position
    Set newCol = tblCols.Add
    newCol.Name = "Last"

    'Insert a column at the third position (after title)
    Set newCol = tblCols.Add(3)
    newCol.Name = "Third"

    'Delete the fifth column (i.e. DOB)
    table.ListColumns(5).Delete

    'Copy only the data in column 1 (excluding the header)
    'We are pasting it in the "Last" column for demo
    table.ListColumns(1).DataBodyRange.Copy (Cells(3, 9))

End Sub

Here is how the above table will look after executing the code

Example 3:  Row operations

In this example let us have a look at some of the row operations in a table. As with columns, you can loop through all the rows, add and delete rows, work with totals row and header row.

Sub excelLists()
    Dim dataSheet As Worksheet
    Dim table As ListObject
    Dim tblRows As ListRows
    Dim tblRow As ListRow
    Dim newRow As ListRow

    Set dataSheet = Sheet2
    Set table = dataSheet.ListObjects("Table5")

    'Get all the Rows of a table
    Set tblRows = table.ListRows

    'Loop through all the Rows of a table
    For Each tblRow In tblRows
        'Display the value in each row for column 1
        'The row index will always start at 1, irrespective of its
        'position on the worksheet
        MsgBox table.DataBodyRange(tblRow.Index, 1)
    Next tblRow

    'Insert a Row at the last position
    tblRows.Add

    'Insert a Row at the third position (excluding header row)
    Set newRow = tblRows.Add(3)

    'Delete the fifth Row (i.e. with ID 5148)
    table.ListRows(5).Delete

    'Display the totals row at the bottom
    table.ShowTotals = True

    'Change color of only the header row
    table.HeaderRowRange.Interior.Color = vbBlue

End Sub

This is how the original table will look like after executing the code

Did you know you can convert this table into text using VBA? Read here to find out more.

See Also:

Excel VBA, Find and List All Files in a Directory and its Subdirectories

Guide to Dictionary Objects

Содержание

  1. VBA ListObject Object in Excel
  2. VBA ListObject Object Methods & Properties
  3. VBA ListObject Object Methods in VBA
  4. Delete
  5. ExportToVisio
  6. Publish
  7. Refresh
  8. Resize
  9. Unlink
  10. Unlist
  11. VBA ListObject object Properties in VBA
  12. Active
  13. AlternativeText
  14. Application
  15. AutoFilter
  16. Comment
  17. Creator
  18. DataBodyRange
  19. DisplayName
  20. DisplayRightToLeft
  21. HeaderRowRange
  22. InsertRowRange
  23. ListColumns
  24. ListRows
  25. Parent
  26. QueryTable
  27. Range
  28. SharePointURL
  29. ShowAutoFilter
  30. ShowAutoFilterDropDown
  31. ShowHeaders
  32. ShowTableStyleColumnStripes
  33. ShowTableStyleFirstColumn
  34. ShowTableStyleLastColumn
  35. ShowTableStyleRowStripes
  36. ShowTotals
  37. Slicers
  38. SourceType
  39. Summary
  40. TableObject
  41. TableStyle
  42. TotalsRowRange
  43. XmlMap
  44. Instructions to Run VBA Macro Code or Procedure:
  45. Other Useful Resources:
  46. VBA ListObjects
  47. What are ListObjects in VBA?
  48. Create Table Format Using ListObjects in Excel VBA
  49. Formatting Excel Tables with VBA ListObjects

VBA ListObject Object in Excel

VBA ListObject Object in Excel. The ListObjects collection contains listobject objet. It represents a object on worksheet and most powerful feature. This object contains different methods and properties. In the following tutorial you learn methods, properties of listobject object. And also learn syntax of it.

VBA ListObject Object Methods & Properties

We have different methods and properties for ListObject Object in Excel VBA.

The methods are Delete, ExportToVisio,Publish, Refresh, Resize, Unlink, and Unlist in Excel VBA.

The properties are Active, AlternativeText, Application, AutoFilter, Comment, Creator, DataBodyRange, DisplayName, DisplayRightToLeft, HeaderRowRange, InsertRowRange, ListColumns, ListRows, Name, Parent, QueryTable, Range, SharePointURL, ShowAutoFilter, ShowAutoFilterDropDown, ShowHeaders, ShowTableStyleColumnStripes, ShowTableStyleFirstColumn, ShowTableStyleLastColumn, ShowTableStyleRowStripes, ShowTotals, Slicers, Sort, SourceType, Summary, TableObject, TableStyle, TotalsRowRange, and XmlMap.

Let us see complete details about methods & properties and.

VBA ListObject Object Methods in VBA

Here are the listobject object methods in VBA. Let us see syntax each method.

Delete

Deletes the ListObject object and clears data on the Worksheet cells.

ExportToVisio

Exports a ListObject object to Visio.

Publish

Publishes the ListObject object to a server that is running Microsoft SharePoint Foundation.

Where
Target is a required parameter. It contains array of strings variant type data.
LinkSource is a required parameter. It contains Boolean type data depending on the target.

Refresh

Retrieves the current data and schema for the list from the server that is running Microsoft SharePoint Foundation.

Resize

The Resize method allows a ListObject object to be resized over a new range. No cells are inserted or moved.

Unlink

Removes the link to a Microsoft SharePoint Foundation site from a list and returns Nothing.

Unlist

Removes the list functionality from a ListObject object. After use, the range of cells that made up the the list will be a regular range of data.

VBA ListObject object Properties in VBA

Let us see the the listobject object properties in VBA. Let us see syntax of each property.

Active

Checks the active cell is inside the range of the ListObject object. It returns a Boolean value indicating whether a ListObject object on a worksheet is active or not. It allows to read only.

AlternativeText

This property returns or sets the descriptive text string for the specified table. It allows to read or write.

Application

It is a property and returns an Application object that represents the Microsoft Excel application.

AutoFilter

It filters a table using the AutoFilter feature. It allows to read only.

This property returns or sets the comment associated with the list object. It is to read or write and string type data.

Creator

It returns a 32-bit integer. It represents the application in which this object was created. It allows to read only and Long type data.

DataBodyRange

It returns a Range object that represents the range of values, excluding the header row, in a table. It allows to read only.

DisplayName

This property returns or sets the display name for the specified ListObject object. It allows to read or write and string type data.

DisplayRightToLeft

True if the specified ListObject is displayed from right to left instead of from left to right. False if the object is displayed from left to right. It allows to read only and Boolean type data.

It returns a Range object that represents the range of the header row for a list. It allows to read only and contains range object.

InsertRowRange

This property returns a Range object representing the Insert row for the specified ListObject object. It allows to read only and contains range object.

ListColumns

It returns a ListColumns collection that represents all the columns in a ListObject object. It allows to read only.

ListRows

It returns a ListRows collection that represents all the columns in a ListObject object. It allows to read only.

This property returns or sets a String value that represents the name of the ListObject object.

Parent

It returns the parent object for the specified object. It allows to read only.

QueryTable

This property returns the QueryTable object that provides a link for the ListObject object to the list server. It allows to read only.

Range

It returns a Range object that represents the range to which the specified list object in the list applies.

SharePointURL

Returns a String representing the URL of the SharePoint list for a given ListObject object. It allows to read only and string type data.

ShowAutoFilter

This property returns Boolean to indicate whether the AutoFilter will be displayed. It allows to read or write and conatins Boolean type data.

ShowAutoFilterDropDown

It returns True when the AutoFilter drop-down for the ListObject object is displayed. It allows to read or write and conatins Boolean type data.

It returns or sets if the header information should be displayed for the specified ListObject object. It allows to read or write and conatins Boolean type data.

ShowTableStyleColumnStripes

This property returns or sets if the Column Stripes table style is used for the specified ListObject object. It allows to read or write and conatins Boolean type data.

ShowTableStyleFirstColumn

It returns or sets if the first column is formatted for the specified ListObject object. It allows to read or write and conatins Boolean type data.

ShowTableStyleLastColumn

It returns or sets if the last column is displayed for the specified ListObject object. It allows to read or write and conatins Boolean type data.

ShowTableStyleRowStripes

This property returns or sets if the Row Stripes table style is used for the specified ListObject object. It allows to read or write and conatins Boolean type data.

ShowTotals

It gets or sets a Boolean to indicate whether the Total row is visible.It allows to read or write and conatins Boolean type data.

Slicers

It returns a list of the table slicers associated with a ListObject. It allows to read.

It gets or sets the sort column or columns and sort order for the ListObject collection.

SourceType

This property returns an XlListObjectSourceType value that represents the current source of the list.

Summary

It returns or sets the description associated with the alternative text string for the specified table. It allows to read or write.

TableObject

This property returns a TableObject object. It allows to read only.

TableStyle

It gets or sets the table style for the specified ListObject object. It allows to read or write and contains variant type data.

TotalsRowRange

This property returns a Range object representing the Total row, if any, from a specified ListObject object. It allows to read only.

XmlMap

It returns an XmlMap object that represents the schema map used for the specified table. It allows to read only.

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

Источник

VBA ListObjects

What are ListObjects in VBA?

In a Table, normally, what we see is a data set. Still, in VBA terminology, there are many more such as there is the range of the total data list range. The column is known as the list column, the row as the list row, and so on. To access these properties, we have an inbuilt function known as ListObjects, used with the worksheet function.

VBA ListObject is a way of referring to the Excel tables while writing the VBA code. Using VBA LISTOBJECTS, we can create and delete tables and play around with Excel Tables in VBA code. However, Excel Tables are tricky for beginners, and even to an extent, intermediate-level users find it difficult to work with Tables. Since this article talks about referencing excel tables Excel Tables In excel, tables are a range with data in rows and columns, and they expand when new data is inserted in the range in any new row or column in the table. To use a table, click on the table and select the data range. read more in VBA coding, you should have good knowledge about Tables in Excel.

When the data converts to tables, we may no longer work with a range of cells. Rather, we need to work with table ranges. So, this article will show you how to work with Excel Tables to write VBA codes Write VBA Codes VBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task. read more efficiently.

Table of contents

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA ListObjects (wallstreetmojo.com)

Create Table Format Using ListObjects in Excel VBA

For example, look at the below Excel data.

Using the VBA ListObject code, we will create a table format for this data.

  • For this data, first, we need to find the last used row and column, so define two variables to find this.

Code:

Code:

  • Now define one more variable to hold the reference of the data.

Code:

  • Now set the reference to this variable by using the below code.

Code:

We need to use the VBA “ListObject.Add” method to create a table; below is the same syntax.

ListObject.Add (Source, XlListObjectHasHeaders, Destination, TableStyleName)

Source: TThis is nothing for which range of cells we are inserting the table. So we can supply two arguments here, i.e., “xlSrcRange” and “xlSrcExternal.”

XlListObjectHasHeaders: If the table inserting data has headers or not. If yes, we can provide “xlYes.” If not, we can provide “xlNo.”

Destination: This is nothing but our data range.

Table Style: We can provide styles if you want to apply any table style.

  • Now in the active sheet, we are creating the table, so the below code would create a table for us.

Code:

  • After this, we need to give a name to this table.

Code:

  • Below is the full code for your reference.

Code:

Let us run the code and see the magic.

It has created the table to the mentioned data and given the table name “EmpTable.”

Formatting Excel Tables with VBA ListObjects

Once we create the Excel table, we can work with tables using the VBA ListObject collection.

  • First, define the variable as “ListObject.”

Code:

  • Now, set the reference to this variable by using the table name.

Code:

Now, the variable “MyTable” holds the reference for the table “EmpTable.”

  • Enter the variable name and put a dot to see the properties and methods of the VBA ListObject.

For example, if we want to select the entire table, then we need to use the “Range” object, and under this, we need to use the “Select” method.

Code:

It would select the entire data table, including the heading.

  • If you want to select only the table contents without headers, we need to use “DataBodyRange.”

Code:

Like this, we can play around with tables.

  • Below is the list of activity codes for your reference.

Code:

Like this, we can use the “ListObject” collection to play around with Excel tables.

Источник

The VBA ArrayList is a much better alternative to the built-in VBA Collection. It contains much richer functionality such as sorting, converting to an array, removing all items etc.

Check out the quick guide for an overview of what the ArrayList does. The rest of this post provides examples of how to use the ArrayList.

Quick Guide to the VBA ArrayList

Task Method Parameters Examples
Access item Item index — long integer value = list.Item(0)
value = list.Item(3)
Access item added last Item index — long integer value = list.Item(list.Count — 1)
Access item added first Item index — long integer value = list.Item(0)
Access all items(For Each) N/A N/A Dim element As Variant
For Each element In fruit
Debug.Print element
Next element
Access all items(For) Item index — long integer Dim i As Long
For i = 0 To list.Count — 1
Debug.Print list.item(i)
Next i
Add item Add object or value list.Add «Apple»
list.Add «Pear»
Copy ArrayList to another ArrayList Clone None Dim list2 As Object
Set list2 = list.Clone
Copy to Array ToArray None Dim arr As Variant
arr = list.ToArray
Copy to a range(row) ToArray None Sheet1.Range(«A1»).Resize(1, list.Count).Value = list.ToArray
Copy to a range(column) ToArray None Sheet1.Range(«A3»).Resize(list.Count, 1).Value = WorksheetFunction.Transpose(list.ToArray)
Create CreateObject «System.Collections.ArrayList» Dim list As Object
Set list = CreateObject(«System.Collections.ArrayList»)
Declare N/A N/A Dim list As Object
Find — check if item exists Contains item to find list.Contains(«Apple»)
Find the position of an item in the ArrayList IndexOf 1. Item to find.
2. Position to start searching from.
Dim index As Long
‘ Search from 0 position
index = fruit.IndexOf(«Pear», 0)
Get number of items Count None totalElements = list.Count
Insert Item Insert 1. Index — position to insert at.
2 Value — object or value to insert.
list.Insert 0, «Peach» ‘ First
list.Insert 1, «Banana» ‘ Second
list.Insert list.Count, «Orange» ‘ Last
Remove all Items Clear None list.Clear
Remove item at position RemoveAt Index — position where the item is list.RemoveAt 0
Remove item by name Remove Item — the item to remove from the ArrayList list.Remove «Apple»
Remove a range of Items RemoveRange 1. Index — starting postion.
2. Count — the number of items to remove.
list.RemoveRange 1,3
Reverse the list Reverse None list.Reverse
Sort in ascending Sort None list.Sort

Description

The ArrayList is similar to the VBA built-in Collection. It is not part of VBA, but it is in an external library which we can access easily. The ArrayList is the same one that is used in the language C#. As you would expect, the ArrayList has a built-in sort, array conversion and other functionality that you would expect in a modern programming language. For the purpose of this article, I will refer to it as the VBA ArrayList.

Download the Source Code

Declare and Create the VBA ArrayList

Like all external libraries we can create the ArrayList using early and late binding.

Late Binding

We use CreateObject to create the ArrayList using late binding:

' https://excelmacromastery.com/
Sub UsingArrayList()

    Dim coll As Object
    Set coll = CreateObject("System.Collections.ArrayList")

End Sub
 

 
The disadvantage of late binding is that we don’t have access to the Intellisense. The advantage is that it is better to use when distributing a VBA application to a user.

Early Binding

Update 12-Nov-2019: Intellisense doesn’t currently work for the ArrayList.
Early binding allows use to use the Intellisense to see what is available to use. We must first add the type library as a reference and then select it from the reference list. We can use the following steps to do this:

  1. Select Tools and then References from the menu.
  2. Click on the Browse.
  3. Find the file mscorlib.tlb and click Open. It should be in a folder like this C:WindowsMicrosoft.NETFrameworkv4.0.30319.
  4. Scroll down the list and check mscorlib.dll.
  5. Click Ok.

 
You can now use the following code to declare the ArrayList using early binding:

Dim coll As New ArrayList

VBA ArrayList Automation Error

You may encounter the VB Run-time Error ‘-2146232576 Automation Error’ when trying to get the ArrayList to work. Or sometimes your code has been working for a long time and then suddenly this error appears.

This is caused by not having the correct .Net Framework version installed. The correct version is 3.5. It doesn’t matter if you have a later version like 4.7, you must have 3.5 installed.

Adding Items to the VBA ArrayList

Adding items to the ArrayList is very similar to how we add them to the Collection. We use the Add method:

' https://excelmacromastery.com/
Sub AddingToList()

    Dim coll As Object
    Set coll = CreateObject("System.Collections.ArrayList")
    
    ' Add items
    coll.Add "Apple" 
    coll.Add "Watermelon"
    coll.Add "Pear"
    coll.Add "Banana"
    
    ' Insert to first position
    coll.Insert 0, "Plum"

End Sub

Reading through an ArrayList

We read through the ArrayList similar to the VBA Collection except that we read from zero to Count-1 rather than from one to Count.

Note: We will use this PrintToImmediateWindow sub in the follow examples to show the contents of the array after the various operations.

' Print all items to the Immediate Window(Ctrl + G)
' Items must be basic data type e.g. Long, String, Double
' https://excelmacromastery.com/
Sub PrintToImmediateWindow(coll As Object)

    Dim i As Long
    For i = 0 To coll.Count - 1
        Debug.Print coll(i)
    Next i
    
End Sub

 
We can use the For Each loop with the VBA ArrayList just like we use it with a Collection:

' Print all items to the Immediate Window(Ctrl + G)
' Items much be basic data type e.g. Long, String, Double
' https://excelmacromastery.com/
Sub PrintToImmediateWindowEach(coll As Object)

    Dim item As Variant
    For Each item In coll
        Debug.Print item
    Next item
    
End Sub

You can download all the code examples at the top of this post.

Sorting

Sort will sort the VBA ArrayList in ascending order.

To sort in descending order simply use Reverse after Sort.

The following code shows an example of sorting in both ascending and descending order:

' https://excelmacromastery.com/
Sub Sorting()

    Dim coll As Object
    Set coll = CreateObject("System.Collections.ArrayList")
    
    ' Add items
    coll.Add "Apple"
    coll.Add "Watermelon"
    coll.Add "Pear"
    coll.Add "Banana"
    coll.Add "Plum"
    
    ' Sort
    coll.Sort
    
    Debug.Print vbCrLf & "Sorted Ascending"
    ' Add this sub from "Reading through the items" section
    PrintToImmediateWindow coll
    
    ' Reverse sort
    coll.Reverse
    
    Debug.Print vbCrLf & "Sorted Descending"
    PrintToImmediateWindow coll
    
End Sub
' https://excelmacromastery.com/
Sub PrintToImmediateWindow(coll As Object)

    Dim i As Long
    For i = 0 To coll.Count - 1
        Debug.Print coll(i)
    Next i
    
End Sub

Cloning the VBA ArrayList

We can create a copy of the ArrayList by using the Clone method. This creates a brand new copy of the ArrayList.

It’s not the same as assigning the variable which means both variables point to the same ArrayList e.g.

' Both variables point to the same ArrayList
Set coll2 = coll

We use Clone like this:

' https://excelmacromastery.com/
Sub Cloning()

    ' Create the ArrayList
    Dim coll1 As Object
    Set coll1 = CreateObject("System.Collections.ArrayList")
    
    ' Add items
    coll1.Add "Apple"
    coll1.Add "Watermelon"
    coll1.Add "Pear"
    coll1.Add "Banana"
    coll1.Add "Plum"
    
    ' Creates a copy of the original ArrayList
    Dim coll2 As Object
    Set coll2 = coll1.Clone
    
    ' Remove all items from coll1
    coll1.Clear
    
    ' Add PrintToImmediateWindow sub from "Reading through the items" section
    Debug.Print vbCrLf & "coll1 Contents are:"
    PrintToImmediateWindow coll1
    
    Debug.Print vbCrLf & "coll2 Contents are:"
    PrintToImmediateWindow coll2

End Sub
' https://excelmacromastery.com/
Sub PrintToImmediateWindow(coll As Object)

    Dim i As Long
    For i = 0 To coll.Count - 1
        Debug.Print coll(i)
    Next i
    
End Sub

Copying from an VBA ArrayList to an Array

We can copy from the ArrayList to an array in one line using the ToArray method:

' https://excelmacromastery.com/
Sub CopyToArray()

    ' Declare and Create ArrayList
    Dim coll As Object
    Set coll = CreateObject("System.Collections.ArrayList")
    
    ' Add items
    coll.Add "Apple"
    coll.Add "Watermelon"
    coll.Add "Pear"
    coll.Add "Banana"
    coll.Add "Plum"
    
    ' Copy to array
    Dim arr As Variant
    arr = coll.ToArray
    
    ' Print the array
    Debug.Print vbCrLf & "Printing the array contents:"
    PrintArrayToImmediate arr
    
End Sub
' Prints the contents of a one dimensional array
' to the Immediate Window(Ctrl + G)
' https://excelmacromastery.com/
Sub PrintArrayToImmediate(arr As Variant)
    
    Dim i As Long
    For i = LBound(arr) To UBound(arr)
        Debug.Print arr(i)
    Next i
       
End Sub

 
You can download all the code examples at the top of this post.
 

Writing Directly to a Range

One of the biggest advantages of the ArrayList is that we can write the contents directly to a range.

The code below writes the contents to both a row and a column:

'  Writes the contents of an ArrayList to a worksheet range
' https://excelmacromastery.com/
Sub ClearArrayList()

    ' Declare and Create ArrayList
    Dim fruit As Object
    Set fruit = CreateObject("System.Collections.ArrayList")
    
    ' Add items
    fruit.Add "Apple"
    fruit.Add "Watermelon"
    fruit.Add "Pear"
    fruit.Add "Banana"
    fruit.Add "Plum"
    fruit.Add "Peach"
    
       
    ' ' Clean existing data
    Sheet1.Cells.ClearContents
    
    ' Write to a row
    Sheet1.Range("C1").Resize(1, fruit.Count).Value = fruit.toArray
    
    ' Write to a column
    Sheet1.Range("A1").Resize(fruit.Count, 1).Value = WorksheetFunction.Transpose(fruit.toArray)
    
End Sub

Array to a VBA ArrayList(1D)

As we have seen, there is an in-built function ToArray which will copy from an ArrayList to an Array.

If we want to copy from an Array to an ArrayList we need to create our own function which I have done below. Because we read through the items one at a time, it may be a bit slow if we have a lot of data:

' https://excelmacromastery.com/
Function ArrayToArrayList(arr As Variant) As Object

    ' Check that array is One Dimensional
    On Error Resume Next
    Dim ret As Long
    ret = -1
    ret = UBound(arr, 2)
    On Error Goto 0
    If ret <> -1 Then
        Err.Raise vbObjectError + 513, "ArrayToArrayList" _
                , "The array can only have one 1 dimension"
    End If

    ' Create the ArrayList
    Dim coll As Object
    Set coll = CreateObject("System.Collections.ArrayList")
    
    ' Add items to the ArrayList
    Dim i As Long
    For i = LBound(arr, 1) To UBound(arr, 1)
        coll.Add arr(i)
    Next i
    
    ' Return the new ArrayList
    Set ArrayToArrayList = coll
    
End Function

 
You can use it like this:

' https://excelmacromastery.com/
Sub ReadFromArray1D()
    
    Dim arr(1 To 3) As Variant
    
    arr(1) = "PeterJ"
    arr(2) = "Jack"
    arr(3) = "Jill"
    
    ' Create the ArrayList
    Dim coll As Object
    Set coll = ArrayToArrayList(arr)

    PrintToImmediateWindow coll
    
End Sub

Remove All Items from the ArrayList

We can remove all the items from an ArrayList by using the Clear function:

' https://excelmacromastery.com/
Sub ClearArrayList()

    ' Declare and Create ArrayList
    Dim coll As Object
    Set coll = CreateObject("System.Collections.ArrayList")
    
    ' Add items
    coll.Add "Apple"
    coll.Add "Watermelon"
    coll.Add "Pear"
    coll.Add "Banana"
    coll.Add "Plum"
    
    Debug.Print vbCrLf & "The number of items is: " & coll.Count
    
    ' Remove all item
    coll.Clear
    
    Debug.Print "The number of items is: " & coll.Count
    
End Sub

 
You can download all the code examples at the top of this post.
 

What’s Next?

Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.

Related Training: Get full access to the Excel VBA training webinars and all the tutorials.

(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)

Like this post? Please share to your friends:
  • What is meaning of odd word
  • What is linking word in english
  • What is mean regarding word
  • What is max rows in excel
  • What is mass word search