Create an Excel Table with a Dynamic Number of Rows Using VBA
Question details
Create an Excel table in VBA when the columns are fixed but the number of data rows varies.

- Product
- Microsoft Excel
- Device & OS
- not provided
- Scenario
- A VBA macro needs to create a table spanning columns A through K without hard-coding the final row.
- Observed behavior
- The table range should extend from the headers in row 1 through the last row containing a record.
Make sure row 1 contains headers and column A has a value for every record, including the last one. Check that the target range does not overlap an existing table and that the name Table1 is available.
Find the Last Data Row and Use It to Create the Table
Use this approach when column A is consistently populated and the table always spans columns A through K.
In Excel, open the workbook and press Alt+F11. In the VBA editor, choose Insert > Module.
Paste this code into the module: Sub CreateDynamicTable() Dim ws As Worksheet Dim tbl As ListObject Dim lastRow As Long Set ws = ActiveSheet lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row If lastRow < 2 Then MsgBox "No data rows were found in column A." Exit Sub End If Set tbl = ws.ListObjects.Add(SourceType:=xlSrcRange, _ Source:=ws.Range("A1:K" & lastRow), _ XlListObjectHasHeaders:=xlYes) tbl.Name = "Table1" tbl.TableStyle = "TableStyleLight13" End Sub
Return to Excel and select the worksheet containing the data. Open Developer > Macros, select CreateDynamicTable, and click Run.
Choose File > Save As and select Excel Macro-Enabled Workbook (*.xlsm) if you want to keep the macro.

Work with Changing Spreadsheet Data in WPS Office
WPS Office is a free, lightweight Office alternative with a familiar interface for editing and formatting spreadsheets. Open compatible Excel files to move everyday spreadsheet work to WPS; check macro compatibility separately before relying on Excel VBA.

Frequently Asked Questions
What does End(xlUp) do in the macro?
Starting at the bottom of column A, ws.Cells(ws.Rows.Count, "A").End(xlUp) finds the last populated cell above it. Its Row property supplies the table's final row.
What if column A is blank in the last record?
Change "A" in the lastRow calculation to a column that is populated for every record. Otherwise, the table may stop before the actual last record.
Why does the macro stop when there are no data rows?
The check lastRow < 2 stops the macro when column A contains only a header or is empty. Add at least one record below row 1 before running it.
What should I do if Table1 already exists?
Change tbl.Name = "Table1" to a unique table name. Also make sure the range A1:K does not overlap an existing Excel table before running the macro.




