|
|||||||
Working with Microsoft Excel tables in VBA
Время создания: 10.10.2019 07:33
Текстовые метки: Таблицы
Раздел: Разные закладки - MSO - Excel
Запись: xintrea/mytetra_db_adgaver_new/master/base/1570681997lqi4161lij/text.html на raw.githubusercontent.com
|
|||||||
|
|||||||
This blog post will be based on working with tables via VBA. They present some unique issues, which has to do with how their structured in the object model. Good or bad, it’s what we have. These are based on my trial and errors, so hopefully this will help somebody out there. That being said I consider this an intermediate level post. If you’re not up to speed with tables, take a look at these: http://excelandaccess.wordpress.com/2013/01/07/why-you-should-use-structured-references-in-tables/ When looking for information about tables, or adding/deleting data, it can be tricky. Here are some pieces of information to keep in mind, which isn’t very obvious, but are cornerstones in working with tables in VBA: · Deleting the DataBodyRange (data portion of a table) will set it to Nothing * · If table parts (i.e. header, totals row) aren’t showing, attempting access will result in an error · Accessing the straight Range of a table includes all visible parts (i.e. [#All]) Tables are ListObjects * If you’ve worked with tables in VBA, you may have noticed that when deleting a table’s entire data body, you are still left with a single, blank row. This is because you must have at least one row of data for the table to still be “alive”. No data rows, no table. You can hide the header and totals row, but you can’t get rid of the body. This presents some interesting coding when working with tables, and can be problematic, aka headache-inducing. * Check the links at the bottom of the post for additional information on these topics. Here are some VBA examples for doing various things with tables in VBA. The file will be available (link at bottom of post) for download. Common variables used throughout Public WS As Worksheet Public loSet As ListObject Public rCols As Range Public iCol As Long Public sMsg As String Public Const sSheetName As String = “Sheet1” As you can see I used some constants for testing in this specific workbook. Change these variables for testing in your environment. I tried to keep the naming convention simple. Getting information from your tables When working with tables via VBA it’s important to know how to look at them, and thus where to go for information. These are some examples of how to get dimension(s) information from your tables. Listing columns This will step through a table and list the column headers in a message box, as well as the Immediate window in the Visual Basic Editor (Ctrl + G to show it). Sub Table_ListColumns() On Error Resume Next If WS Is Nothing Or loTest Is Nothing Then sMsg = vbNullString MsgBox sMsg, vbOKOnly, “COLUMN HEADERS” End Sub
Column count This will not loop through the table, but give a straight count of columns, along with which/where the start/end columns are. Sub Table_CountColumns() On Error Resume Next If WS Is Nothing Or loTest Is Nothing Then sMsg = “There are ” & loTest.ListColumns.Count & ” columns in ‘” & sTableName & “‘.” MsgBox sMsg, vbInformation, UCase(sTableName) End Sub
Row count Again, no loop, just find out how many rows are in the table and where they are. Sub Table_CountRows() On Error Resume Next If WS Is Nothing Or loTest Is Nothing Then sMsg = “There are ” & loTest.ListRows.Count & ” rows in ‘” & sTableName & “‘.” MsgBox sMsg, vbInformation, UCase(sTableName) End Sub
Resizing Tables Resize table based on original This will basically clear out the manual data and leave the formulas. It gets a row count and uses that to insert rows to its original size. Please note these focus on resizing rows programmatically, not columns, which can be trickier. Sub ResizeTableRows() ‘/// Set misc variables ‘/// Ensure the table has a data range ‘/// Get the number of rows in the table ‘/// Delete destination table data ‘/// Resize to source table size ‘/////////////////////////////////////////////////////////////////////////// End Sub
Resize table based on another tables size (in rows) This utilizes two tables. The second table is only used for its row size and makes the first table the same size. It deletes the DataBodyRange as well, so all manual data will be erased, leaving only formulas. Sub ResizeTableRowsBasedOnAnother() ‘/// Set misc variables ‘/// Set two tables, one to set (destination) ‘/// Delete destination table data ‘/// Ensure source table has data range ‘/// Resize to source table size ‘/////////////////////////////////////////////////////////////////////////// End Sub Resize table columns This example will add a single column. While I am very hesitant to code something like this, here is an example. While it’s easier to add rows, adding columns present some unique problems, which include: · Where should the columns be inserted? · Without proper absolute structured formula referencing, this could throw off formulas · Ideally no data should be to the right of the table, so an error won’t be thrown. Sub ResizeTableCols() ‘/// Set misc variables ‘/// Ensure the table has a data range ‘/// Get the number of columns in the table, add one ‘/// Delete destination table data ‘/// Resize to source table size ‘/////////////////////////////////////////////////////////////////////////// End Sub
Select table parts Table ranges It’s always best to work with actual table range referernces. While you can access the range object of the underlying worksheet, it gets tough. This shows an example. Sub ListTableParts() ‘/// Set misc variables If loSet.DataBodyRange Is Nothing Then ‘/// Using standard table referencing objects ‘/// Using range referencing objects MsgBox sMsg, vbInformation, “INFO” End Sub Select table Header This selects just the header range of the table, if it is showing. If it’s not showing the user gets the option to show it at that time. Sub SelectHeader() ‘/// Set misc variables If Not loSet.HeaderRowRange Is Nothing Then End Sub Select table data This selects just the data range of the table, if it is not deleted. If it’s not there the user gets the option to add it at that time. NOTE: Adding a data body (DataBodyRange) to a table is as simple as inserting a row. This is quite a useful trick when working with tables via VBA. Sub SelectData() ‘/// Set misc variables If Not loSet.DataBodyRange Is Nothing Then End Sub Select table Totals row This selects just the totals row range of the table, if it is showing. If it’s not showing the user gets the option to show it at that time. Sub SelectTotalRow() ‘/// Set misc variables If Not loSet.TotalsRowRange Is Nothing Then End Sub Show table parts This routine has a Boolean (True/False) variable passed to it to turn on or off all table parts (non-formatting) Sub ShowTableParts(Optional ByVal bState As Boolean = True) ‘/// Set misc variables loSet.ShowTotals = bState End Sub Note that the ShowAutoFilter portion only runs if a True variable is passed (turning properties on). This is because if you turn off the header row, there’s nothing to filter on, so there’s no need to worry about it. Summary The important parts of the object model to look at with respect to tables are: · ListObject · DataBodyRange · HeaderRowRange · TotalsRowRange · ListRows · ListColumns There are other things you can do with tables via VBA, this certainly isn’t the complete guide. Some of those things include: · Work with slicers * · Unlist it (convert to standard range) · Set style/formatting options |
|||||||
Так же в этом разделе:
|
|||||||
|
|||||||
|