Using a Macro to Select a Modified Table Body

by Allen Wyatt
(last updated January 19, 2018)

3

Mike has an Excel table defined and he wants to select just the data portion of the table using VBA. He knows he can use the DataBodyRange.Select method, but this just seems to select everything apart from the header row. In Mike's table the first row contains headings, the last row and last column contain formulas, and the first column contains row headings, so he wants to exclude these from the selection. The table can expand both by rows and columns, so he needs some way to select this data dynamically. Any thoughts on how this can be done?

You create defined tables (as Mike mentions) by using the Table tool on the Insert tab of the ribbon. I normally find it best to enter my column headings and my data, put any summary formulas in the last column of the table, but don't put them in the last row. I then select a cell in the table and use the Table tool to define the entire area of the table.

Once a table is defined in this manner, you can then use the Design tab of the ribbon to modify how Excel sees your table. Click the tab and make sure, in the Table Style Options group, that you specify your table has a Header Row, Total Row, First Column (for your column headers), and Last Column (for your summary formulas). You can then use a macro such as the following to figure out and select the table body:

Sub SelectTableBody()
    Dim rTableData As Range

    With ThisWorkbook.Worksheets(1)
        Set rTableData = .ListObjects("Table1").DataBodyRange
        Set rTableData = rTableData.Offset(0, 1) _
          .Resize(, rTableData.Columns.Count - 2)
    End With

    rTableData.Select
End Sub

The first Set statement sets the rTableData range equal to what Excel considers the body of the data table. This includes everything except the header and the total row. (Why Excel includes the first column and the last column when you've designed those columns to be special beats me.) The next Set statement then adjusts the range inward by one column on the left and one column on the right. The result is that rTableData represents just the data range that you want.

This approach is dynamic in nature, meaning that it will adjust automatically (well, each time you run it) whenever you add or delete table rows or column. It will not adjust properly if you happen to delete either the first or last columns of your data table; it assumes those columns will never be part of the body range you want.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (8730) applies to Microsoft Excel 2007, 2010, and 2013.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He  is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Referring to the Last Cell

It is not unusual to use worksheets to collect information over time. As you keep adding information to the worksheet, ...

Discover More

Shortcut for Show/Hide

Hate to take your hands off the keyboard? Here's a handy keyboard shortcut you can use to display (or not display) the ...

Discover More

Sorting Decimal Values

Government and industrial organizations often use a numbering system that relies upon a number both before and after a ...

Discover More

Program Successfully in Excel! John Walkenbach's name is synonymous with excellence in deciphering complex technical topics. With this comprehensive guide, "Mr. Spreadsheet" shows how to maximize your Excel experience using professional spreadsheet application development tips from his own personal bookshelf. Check out Excel 2013 Power Programming with VBA today!

More ExcelTips (ribbon)

Resizing Checkboxes

If you create a user form in VBA that includes checkboxes, you may want to make the checkboxes larger. You can't adjust ...

Discover More

Sheets for Months

One common type of workbook used in offices is one that contains a single worksheet for each month of the year. If you ...

Discover More

Reorganizing Data

If you need to consolidate a single column of data into multiple columns of data, you'll love this macro. It provides a ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 3 - 2?

2018-01-19 07:20:07

Mark

Allen, I look forward to receiving your ExcelTips email every day because they are generally informative and accurate.

However, I think you've missed on both points today.

Table Styles don't affect how Excel sees a table - they just make them look different.

Excel introduced ListBoxes in Excel 2007 which, in VBA, had to be addressed as using the ListObject object. This was fairly cumbersome for coders so I just stuck with my named ranges some of which were dynamic using OFFSET and COUNT formulas.

In Excel 2010, those list boxes became tables and "structured references" were available in both Excel and VBA. A "structured reference" in Excel could look like =SUM(Table1[Totals]) to get the SUM of the Totals column in Table1. You don't even need a Total row at the bottom of the table. Your Totals column could have a formula like =SUM(Table1[@[Col1]:[Col12]]). The @ tells excel to reference the row you are on.

In VBA you could reference WorksheetFunction.SUM(Range("Table1[Totals]")) because Excel automatically sees the structured reference as a Range Name.

You can also use a shorter structured reference in VBA - WorksheetFunction.SUM([Table1[Totals]]). The square bracketing of a [RangeName] is seen in VBA the same as Range("Table1[Totals]"). BTW, You can use this abbreviated referencing to refer to cells as Sheet1.[A1] in code where Sheet1 is the Codename of the sheet, not the actual tab name.

If you want do something with a subset of Table1 in VBA you could refer to [Table1[Col2]:[Col12]] where Col1 and Col12 are the headings of the columns. So there isn't any need to use an OFFSET to redefine the range you want to work with.


2016-04-15 07:16:09

Carla

Can you tell me how to add a box like this one? I need to make an area for others to add their text to a saved/protected sheet.


2014-03-03 10:13:37

Bryan

"Why Excel includes the first column and the last column when you've designed those columns to be special beats me."

Well, the help files clearly state that ListObject.DataBodyRange includes everything but the headers. How is Excel supposed to know when you have denoted a column as "special", when there isn't a "special" button?

Perhaps Mike and Allen are confused by the "First Column" and "Last Column" options in the Design tab when you select a table. These refer only to the *formatting*, not to the data. If you were to manually, say, italicize the entire last column, then you would likely be very confused if all the sudden DataBodyRange didn't include that last column.


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.