Vba delete table excel

VBA Delete Table from Worksheet & Workbook in Excel. This means deleting or removing the table on Worksheet in Excel using VBA. Here we use the ListObjects collection and Delete method to delete table. And also see how to delete multiple tables on worksheet and active Workbook. In this tutorial let us learn the example and step by step instructions to delete table on the worksheet.

Table of Formats:

  • Objective
  • Syntax to Delet Table using VBA in Excel VBA
  • Example to delete Table on the Worksheet in Excel
  • Delete all Tables on the Worksheet in Excel
  • All Tables Delete from the WorkBook in Excel
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

Syntax to Delete Table using VBA in Excel

Here is the syntax to delete table on the worksheet using VBA in Excel.

Expression.ListObjects(TableName).Delete

Example to Delete Table on the Worksheet in Excel VBA

Let us see the example to delete or remove table on the worksheet. The sheet name defined as ‘Table‘. And we use table name as ‘MyDynamicTable‘. You can change these two as per your requirement. Where Delete method is used to delete table on Worksheet.

'Delete Table using VBA in Excel
Sub VBAF1_Delete_Table()
     
    'Declare Variables
    Dim sTableName As String
    Dim sSheetName As String
    
    'Define Variables
    sSheetName = "Table"
    sTableName = "MyDynamicTable"
    
    'Delete Table
     Sheets(sSheetName).ListObjects(sTableName).Delete
     
 End Sub

Output: The table is deleted on the Worksheet.

Delete all Tables on the Worksheet in Excel

The following VBA code helps to delete all tables on the worksheet. The below code loop through all tables to delete on the worksheet.

'VBA Delete all Tables on Worksheet
Sub VBAF1_Delete_All_Tables_On_Worksheet()
     
    'Declare Variables
    Dim loTable As ListObject
    Dim sTableName As String
    Dim oSheetNameAs Worksheet
    
    'Define Variables
    oSheetName= "MyDynamicTable"
    
    'Set Sheet object
    Set sSheetName = Sheets("Table")
        
     'Loop through each table in worksheet
     For Each loTable In oSheetName.ListObjects
     
         'Define Table Name
         sTableName = loTable.Name
 
         'Delete Table
          oSheetName.ListObjects(sTableName).Delete
     
     Next loTable
            
 End Sub

Output: The above code deleted all tables on the worksheet named Table.

All Tables Delete from the Workbook in Excel

Let us see how to delete all tables delete from the Workbook in Excel using VBA. The below code loop through all workbooks to delete tables from all sheets.

'VBA Delete all Tables from Workbook
Sub VBAF1_Delete_All_Tables_from_Workbook()
     
    'Declare Variables
    Dim loTable As ListObject
    Dim sTableName As String
    Dim oSheetName As Worksheet
    
    'Define Variables
    sTableName = "MyDynamicTable"
    
    'Set Sheet object
    Set oSheetName = Sheets("Table")
    
    'Loop through each table in worksheet
     For Each oSheetName In ActiveWorkbook.Worksheets
     
        'Loop through each table in worksheet
        For Each loTable In oSheetName.ListObjects
        
            'Define Table Name
            sTableName = loTable.Name
    
            'Delete Table
             oSheetName.ListObjects(sTableName).Delete
        
        Next loTable
        
     Next oSheetName
            
 End Sub

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

I would like to delete a table from Excel including the header, first row and totals.

I have the table name defined as a string (TableName).

I have found

Range(TableName).Delete

Will delete the DataBodyrange but leave the headings and first row. And

Range(TableName).ListObject.Delete

Will delete the whole table but leave blank space behind.

What code do I need to delete the entire table and leave no blank space?

asked Dec 14, 2017 at 21:47

EllBrandon's user avatar

4

You can do it separately (in fact as far as I can remember, you have to). In my example you don’t know the location of the table, but if you do know the starting cell then obviously you can put a constant in instead of firstrow and firstcol.

Sub deltable()
Dim lastrow As Long
Dim firstrow As Long
Dim firstcol As Long
Dim lastcol As Long
Dim mytable As ListObject

    Set mytable = Sheets("Sheet1").ListObjects("Table3")

    firstrow = mytable.ListRows(1).Range.Row - 1
    lastrow = mytable.ListRows.Count + firstrow + 1
    firstcol = mytable.ListColumns(1).Range.Column - 1
    lastcol = mytable.ListRows.Count + firstcol + 1

    mytable.Unlist

    Sheets("Sheet1").Range(Cells(firstrow, firstcol), Cells(lastrow, lastcol)).Delete shift:=xlUp

End Sub

answered Dec 14, 2017 at 23:17

Carol's user avatar

CarolCarol

4714 silver badges7 bronze badges

2

There are times in Excel when you may wish to create a table on the fly with the assistance of VBA code. I was in this position recently and needed to this with VBA. A file was uploaded into a sheet and the task was to create a table and then use that table for more data manipulation. The following Excel VBA procedure was what I ended up with.

Option Explicit

Sub

NewTable() ‘Excel VBA to create a table if there is none.
Dim ListObj As ListObject
Dim
sTable As String

sTable = «DataTable»

   Set ListObj = ActiveSheet.ListObjects.Add(xlSrcRange, [A1].CurrentRegion, , xlYes)
   ListObj.Name = sTable
‘The name for the table

End Sub

To complicate the procedure there was also a possibility that a table had been created by an end user, so I needed to test for the table in which case the code needed to become more complex. The following procedure will remove a table but will keep the formatting of the table so it looks like a table but performs like a normal Excel range.

Sub RemTable() ‘Remove table, keep table format.

      Sheet1.ListObjects(1) .Unlist

End Sub

While the following will remove the table and the formatting of the table, so it is just like a worksheet with regular data.

Sub RemTableandFormat() ‘Using the Activesheet for variety.
      ActiveSheet.ListObjects(«MyData»).Unlist
      [A1].CurrentRegion.ClearFormats
End Sub

In both procedures the ListObjects(1) assumes that on sheet1 (the worksheet code name not the sheet name) there is 1 table.

If you are trying to trap the name of a table the following might come in handy. WOrking with the name of the table after it has been created can help with referencing the table at a later point.

Sub TableName() ‘Assign the table name to a string
Dim strName As String

strName = Sheet1.ListObjects(1).Name
End Sub

Содержание

  1. Access VBA Tables – Update, Count, Delete, Create, Rename, Export
  2. Access VBA Tables
  3. Create Table
  4. Close Table
  5. Delete Table
  6. Rename Table:
  7. Empty / Clear Table
  8. VBA Coding Made Easy
  9. Truncate Table / Delete Records
  10. Export Table to Excel
  11. Update Table
  12. Access VBA Table Functions
  13. Count Table Records
  14. Check if Table Exists Function
  15. Create Table Function
  16. Delete / Drop Table Function
  17. Empty Table Function
  18. Rename Table Function
  19. Truncate / Delete Records from Table
  20. Export Table to Excel
  21. Add / Append Records to a Table
  22. Add Record to Table From Form
  23. VBA Code Examples Add-in
  24. Access VBA delete Table using DoCmd.DeleteObject Method
  25. Access VBA delete Table
  26. Example 1 – Access VBA delete Table (delete single Table)
  27. Example 2 – Access VBA delete Table (delete all Table)
  28. Example 3 – Access VBA delete Table (delete specific Table)
  29. 2 thoughts on “ Access VBA delete Table using DoCmd.DeleteObject Method ”
  30. Access VBA delete Table records with SQL using DoCMD.RunSQL Method
  31. Access delete Table records
  32. Access VBA delete Table records
  33. DEVelopers HUT
  34. DoCmd DeleteObject Method
  35. SQL DROP Statement
  36. TableDefs Delete Method
  37. Making It Into A Function
  38. A Few Resources on the Subject
  39. Leave a Reply Cancel reply
  40. My YouTube Channel
  41. About the Author
  42. Recent Posts
  43. Categories
  44. Archives
  45. VBA Delete Table in Excel
  46. Syntax to Delete Table using VBA in Excel
  47. Example to Delete Table on the Worksheet in Excel VBA
  48. Delete all Tables on the Worksheet in Excel
  49. All Tables Delete from the Workbook in Excel
  50. Instructions to Run VBA Macro Code or Procedure:
  51. Other Useful Resources:

Access VBA Tables – Update, Count, Delete, Create, Rename, Export

This tutorial will teach you how to work with Access Tables using VBA.

Access VBA Tables

To start we will demonstrate the simple commands for working with Tables in Access. Later in this tutorial we will show you full professionally developed functions for working with tables in Access.

Create Table

This code will use SQL to create a table named “Table1” with fields “ID” and “Name”:

Close Table

This line of VBA code will close a Table (saving changes):

To close a Table without saving:

Delete Table

This code will delete a Table (note: first the Table should be closed):

Rename Table:

This line of code will rename an Access Table:

Another option is using the TableDefs property of a database object.

Empty / Clear Table

This VBA code will empty a Table:

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!

Truncate Table / Delete Records

This line of VBA code uses SQL to delete records from a table that meet certain criteria:

Export Table to Excel

To export a Table to Excel use the DoCmd.OutputTo method:

or use the DoCmd.TransferSpreadsheet method:

Update Table

The following code will update a record, without displaying the warning message:

Access VBA Table Functions

The above code examples are the simple commands you can use to interact with Tables using VBA. However, you will often need to add much more supporting code (including error handling) to properly utilize these commands. Below you will find professionally develop functions for working with Tables in Access.

Count Table Records

This function will count the number of records in a table:

Check if Table Exists Function

This Function will test if a table exists, returning TRUE or FALSE:

Here is an example of the function in use:

Create Table Function

This function will create a Table in Access VBA in the Current Database:

This Function will return TRUE if the table is created successfully or FALSE if the table is not created.

You can call the function like this:

Delete / Drop Table Function

This function will delete a table if it exists:

You can call the function like this:

Empty Table Function

This function will empty a table if it exists:

You can call the function like this:

Rename Table Function

This VBA function will rename a table:

You can call the function like this:

Truncate / Delete Records from Table

This function will delete records from a table with error handling:

Export Table to Excel

This line of code will export a Table to Excel (a new spreadsheet):

Or you can use this function:

The above code will export to a new spreadsheet. Instead you can add a table to an existing spreadsheet. Our article on Importing / Exporting in Access VBA covers this in more detail.

Add / Append Records to a Table

This function will add / append a record to a table:

Add Record to Table From Form

This function will add a record to a table from a form:

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

Access VBA delete Table using DoCmd.DeleteObject Method

This Access VBA tutorial explains how to delete Table (delete single table, delete multiple tables) in VBA using DoCmd.DeleteObject Method.

You may also want to read:

Access VBA delete Table

In Access VBA, deleting Table can be done by DoCmd.DeleteObject Method. It is an extremely simple and straight forward, the syntax is as below. In order to delete Table, use acTable in the ObjectType argument.

Name Required/Optional Data Type Description
ObjectType Optional AcObjectType
Name Value Description
acDatabaseProperties 11 Database property
acDefault -1
acDiagram 8 Database Diagram (Microsoft Access project)
acForm 2 Form
acFunction 10 Function
acMacro 4 Macro
acModule 5 Module
acQuery 1 Query
acReport 3 Report
acServerView 7 Server View
acStoredProcedure 9 Stored Procedure (Microsoft Access project)
acTable 0 Table
acTableDataMacro 12 Data macro
ObjectName Optional Variant string expression that’s the valid name of an object of the type selected by the objecttype argument. If you run Visual Basic code containing the DeleteObject method in a library database, Microsoft Access looks for the object with this name first in the library database, then in the current database.

Example 1 – Access VBA delete Table (delete single Table)

The below Macro deletes a Table called Table1. Unlike deleting Table manually, there is no alert to ask you to confirm deletion, meaning you don’t have to write extra code to disable alert.

Example 2 – Access VBA delete Table (delete all Table)

The below Procedure will loop through all Tables and delete them. Click here to see my previous post for more detailed explanation.

Example 3 – Access VBA delete Table (delete specific Table)

In the above example, I use LIKE to exclude system tables from our deletion, because it would cause an error message to pop up. Similarly, we can use LIKE to to indicate what Table name to delete.

In the below example, all the Tables that have prefix Employee in the name will be deleted.

2 thoughts on “ Access VBA delete Table using DoCmd.DeleteObject Method ”

hello, so i’ve got the beginning and the end. How can i execute a query for all tbl_temp ? the difficulty is to replace the table name in the query. I think i have to do a loop, but the code for all the steps is too difficult for me.

Can you help me ?

Have a good day.

Can you tell me what name you want to replace with?

Источник

Access VBA delete Table records with SQL using DoCMD.RunSQL Method

This Access VBA tutorial explains how to use VBA delete Table records with SQL without alert using DoCMD.RunSQL Method.

You may also want to read:

Access delete Table records

In my previous post, I have explained how to delete Table records without using VBA, below is a quick recap.

Suppose we have created a table called student in Access, which contains 5 student records.

student

Student ID Student Name
001 Apple
002 Betty
003 Cathy
004 David
005 Elyse

In order to delete the record (the whole row) of Apple, create a new Query, add student table.

Under Design tab, click on Delete button. This will create a Delete Query.

Add Student ID to the field, then type “001” in criteria, which is the student ID of Apple.

To preview the result of Delete Query (which records will be deleted), click on the View button under Design.

To execute the Query (actually delete the records), click on Run button, then click on Yes to confirm delete row.

Access VBA delete Table records

Similar to executing Delete Query in Access UI, you can delete Access Table records in VBA. First write a standard Delete SQL statement, then use DoCMD.RunSQL Method to execute the SQL.

For example, we have a student Table as below.

student

Student ID Student Name
001 Apple
002 Betty
003 Cathy
004 David
005 Elyse

Press ALT+F11 and insert the below code in Module.

Writing DoCmd.SetWarings False is because we want to avoid Access generating the below Alert so that the subsequent statements can be executed smoothly.

Run the Sub, then you will see the below result where Student ID 002 is deleted.

Источник

DEVelopers HUT

There are 3 approaches that come to mind for deleting a table in Microsoft Access:

DoCmd DeleteObject Method

SQL DROP Statement

TableDefs Delete Method

RefreshDatabaseWindow does as its name implies and will update the navigation pane’s table listing to reflect the deletion. If you omit this command the table will remain in the listing until you reopen that database.

Making It Into A Function

As with most coding, basic built-in functions it is often best to build your own procedure around them to trap common error and return a Boolean value to indicate whether or not the process executed successfully or not.

Below is a reusable function which illustrates exactly that for the DeleteObject Method.

Below is a reusable function which illustrates exactly that for the TableDefsDelete Method.

A Few Resources on the Subject

Leave a Reply Cancel reply

If you found this site helpful, consider giving a donation to offset the costs to keeping it running and thank you.

My YouTube Channel

Be sure to check out my latest videos on Access, Excel, VBA and more . by visiting:

Recent Posts

Categories

Archives

DevHut is provided graciously by CARDA Consultants Inc.

Like most sites on the Internet, this site uses cookies to collect data on usage (comments, downloads, post views, etc…) to improve your experience. By continuing to browse this site you consent to this policy.

All code samples, downloads, links, …, everything on this site is provided ‘AS IS‘ and without any guarantees or warrantee. You assume the risks if you choose to try any of the code, samples, etc. provided on this site.

Источник

VBA Delete Table in Excel

VBA Delete Table from Worksheet & Workbook in Excel. This means deleting or removing the table on Worksheet in Excel using VBA. Here we use the ListObjects collection and Delete method to delete table. And also see how to delete multiple tables on worksheet and active Workbook. In this tutorial let us learn the example and step by step instructions to delete table on the worksheet.

Syntax to Delete Table using VBA in Excel

Here is the syntax to delete table on the worksheet using VBA in Excel.

Example to Delete Table on the Worksheet in Excel VBA

Let us see the example to delete or remove table on the worksheet. The sheet name defined as ‘Table‘. And we use table name as ‘MyDynamicTable‘. You can change these two as per your requirement. Where Delete method is used to delete table on Worksheet.

Output: The table is deleted on the Worksheet.

Delete all Tables on the Worksheet in Excel

The following VBA code helps to delete all tables on the worksheet. The below code loop through all tables to delete on the worksheet.

Output: The above code deleted all tables on the worksheet named Table.

All Tables Delete from the Workbook in Excel

Let us see how to delete all tables delete from the Workbook in Excel using VBA. The below code loop through all workbooks to delete tables from all sheets.

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.

Источник

  • #2

To delete a table and its data, try…

Code:

ActiveSheet.ListObjects("MyData").Delete

To delete a table without losing its data or table formatting, try…

Code:

ActiveSheet.ListObjects("MyData").Unlist

In the following code, if a table named «MyData» does not exist, it creates one…

Code:

Option Explicit

Sub test()

    Dim ListObj As ListObject
    
    On Error Resume Next
    Set ListObj = ActiveSheet.ListObjects("MyData")
    On Error GoTo 0
    
    If ListObj Is Nothing Then
        Set ListObj = ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A$3:$J$50"), , xlYes)
        ListObj.Name = "MyData"
    End If

End Sub

  • #5

So, call me a stickler. #1. I don’t like code that relies upon generating an error to work, and #2. I don’t like magic «numbers» (or strings). So, if you’re like me, use this code instead:

Code:

Option Explicit

Sub test()

    Dim ListObj As ListObject
    Dim MyName As String
    Dim MyRangeString As String
    Dim MyListExists As Boolean

    MyName = "MyData"
    MyRangeString = "$A$3:$J$50"

    MyListExists = False
    For Each ListObj In ActiveSheet.ListObjects
       
        If ListObj.Name = MyName Then MyListExists = True
        
    Next ListObj
    
    If Not(MyListExists) Then
        Set ListObj = ActiveSheet.ListObjects.Add(xlSrcRange, Range(MyRangeString), , xlYes)
        ListObj.Name = MyName
    End If

End Sub

This doesn’t rely on an error being generated to detect it doesn’t exist.
This also has the advantage that you can change the variable «MyName» to check for other tables, or even loop through a set of names.
Same with MyRangeString, if your range changes (better would be to calculate it somehow)

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

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 macro recorder is a really wonderful tool, especially when you want to get an insight into an unfamiliar part of the Excel object model. However, it’s notorious for producing inefficient code – and clearing a table is a typical example.

I’ve created a simple table called Table1 in Excel 2010 with four columns.

The first three columns contain constants and Col4 contains this formula:

=[@Col2]+[@Col3]

I want to clear this table as part of my VBA automation code so, to get an idea of the code involved, I do it manually with the macro recorder turned on. I clear the table by selecting all the data in Col1, right-click > Delete > Table Rows.  The output looks like this:

Sub Macro1()
'
' Macro1 Macro
'

'
    Range("Table1[Col1]").Select
    Selection.ListObject.ListRows(1).Delete
    Selection.ListObject.ListRows(1).Delete
    Selection.ListObject.ListRows(1).Delete
    Selection.ListObject.ListRows(1).Delete
    Selection.ListObject.ListRows(1).Delete
End Sub

The first thing that is evident is that this code isn’t going to work unless there are five rows of data in the table, but we can take the hint from the macro recorder that we’re interested in ListObject.ListRows (in the Excel Object Model a table is a ListObject) and introduce the flexibility we need. While we’re at it we can remove the Selection object too – perhaps ending up with something like this:

Sub Macro2()

    With Sheet1.ListObjects("Table1").ListRows
        Do While .Count >= 1
            .Item(1).Delete
        Loop
    End With

End Sub

That code is fine and it does exactly what it says on the tin, but you’ll find that if the table is very large then the code will be slow – even if you turn off Application.ScreenUpdating.

The rule of thumb is that, when you’re deleting rows or columns in Excel, it’s much quicker to delete them all in one go and not one at a time – I’ll explain why this is in a future blog post about deleting worksheet rows. The macro recorder has slightly mislead us with its naive ListObject.ListRows property suggestion because we can do this task much more efficiently using the ListObject.DataBodyRange property instead (again, I’m not including optimisations such as setting Application.ScreenUpdating to False):

Sub Macro3()

    With Sheet1.ListObjects("Table1")
        If Not .DataBodyRange Is Nothing Then
            .DataBodyRange.Delete
        End If
    End With

End Sub

Once the table has been cleared you’ll notice that, if you start to put data back into it, it remembers the formulae in Col4 and automatically puts them back in for you. In the below screenshot I’ve just typed in “a” in Col1.

This behaviour is built into tables and hidden away in their inner workings: as far as I can tell, there isn’t an exposed Application or ListObject property we can use to control it. One property which looks like it might fit the bill is Application.AutoCorrect. AutoFillFormulasInLists, but this setting controls whether or not a formula is filled down the entire ListColumn once it has been entered. Incidentally, why does this setting (along with AutoExpandListRange) need to be at the Application level? It’d be so much more useful if it could be controlled on a table by table basis at the ListObject level.

If you want to stop the table from remembering formulae when you clear it then one way I’ve found is to clear the contents of the data body range before deleting it:

Sub Macro4()

    With Sheet1.ListObjects("Table1")
        If Not .DataBodyRange Is Nothing Then
            .DataBodyRange.ClearContents
            .DataBodyRange.Delete
        End If
    End With

End Sub

It’s true that you could just delete the table entirely and then create a new one, but that may not be a viable option if you have formulae and the such which reference the table.

About Colin Legg

RAD Developer

Microsoft MVP — Excel
2009 — 2014

Like this post? Please share to your friends:
  • Vba delete row from excel
  • Vba date picker excel
  • Vba copy row excel vba
  • Vba copy formatting excel
  • Vba convert word to text