[Excel VBA] How to Convert a Cell Range to a Table (ListObject)

In Excel, converting tabular data into a Table (ListObject) allows you to utilize many features such as filtering, sorting, and structured references.

This article explains how to use VBA to convert an existing cell range into a table and how to assign a specific name to that table.

目次

Intended Use Cases

  • Automatically convert a data input range into a table for easier organization and analysis.
  • Set a table name via VBA to make it easier to reference from other macros.
  • Automate routine tasks to reduce errors and save time.

VBA Code Example

The following code converts the cell range B3:E8 into a table format and names it “CustomerList“.

Sub ConvertRangeToTable()

    Dim dataArea As Range
    Dim tbl As ListObject

    ' Set the data range (including headers)
    Set dataArea = ActiveSheet.Range("B3:E8")

    ' Create the table and set parameters
    Set tbl = ActiveSheet.ListObjects.Add(SourceType:=xlSrcRange, _
                                          Source:=dataArea, _
                                          XlListObjectHasHeaders:=xlYes)

    ' Set the table name
    tbl.Name = "CustomerList"

End Sub

Key Points of the Code

ItemDescription
ListObjects.Add(…)Inserts the specified range as a table.
SourceType:=xlSrcRangeExplicitly states that the source is a cell range.
XlListObjectHasHeaders:=xlYesSpecifies that the range includes a header row.
.Name = “CustomerList”Sets a custom name for the created table.

Important Notes

  1. Include Headers: Be sure to include the header row in your range specification. When xlYes is specified, the first row is recognized as column names.
  2. Unique Names: The table name must be unique within the workbook. If a table with the same name already exists, an error will occur.
  3. Structured References: After converting to a table, structured references become available (e.g., formulas like =CustomerList[Age]).

Application Examples

  • A macro that batch-converts lists across multiple sheets into tables.
  • Automatically applying specific colors or styles after creating a table.
  • Automatically creating summaries or charts based on the new table.

Summary

Using VBA, you can convert any cell range into a table format with a single click, significantly improving both appearance and functionality.

Additionally, by specifying a table name, you make it much easier to call and manipulate the data in subsequent processing or other macros. If you want to leverage Excel “Tables” for your data, please try this method.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次