Vba tables in vba in Excel
The Excel tables are accessed in VBA using the ListObjects Object.
The "Listobjects" returns a "Listobject" which represents an Excel Table.
However, "Listobjects" is used to access an already existing table.
Create Table
The following example shows, how to create a new table in excel.
- Sub CreateNewTable()
- Sheets("Q49").ListObjects.Add(xlSrcRange, Range("K1:N10"), , xlYes).Name = "myTable1"
- End Sub
The above example creates a plain table as shown in the right.
Convert to Range
The following code shows how to convert the table to Normal range.
- Sub tabletorange()
- On Error Resume Next
- Sheets("Q49").ListObjects("myTable1").Unlist
- End Sub
Loop through Table
The following code shows loops through each Table column/row
- Sub tableloop()
- Dim tbl As ListObject
- Dim x As Long
- Set tbl = ActiveSheet.ListObjects("myTable1")
- On Error Resume Next
- '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
Clear Filter in Table
The following code shows how to clear filter in Table headers
- Sub sbClrFtr()
- If Sheets("Q49").FilterMode = True Then
- Sheets("Q49").ListObjects("myTable1").Range.AutoFilter
- End If
- End Sub
A screeenshot of the sample table is shown below