Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA extend table when data added below table

Tags:

excel

vba

I have a table in Excel that when users add data after the table, the data doesn't belong to the table.

I've created a code that can be executed to extend the table. The code is as follows:

Sub ExtendTableToLastRow()

    Sheets("Update").Select
    If ActiveSheet.FilterMode Then ActiveSheet.AutoFilter.ShowAllData
    'LastRow = Cells(Rows.Count, 1).End(xlUp).Row
    LastRow = ActiveSheet.Range("a1").Offset(ActiveSheet.Rows.Count - 1, 0).End(xlUp).Row

    ActiveSheet.ListObjects("TUpdate").Resize Range("$A$2:$AK$" & LastRow)
    Range("A1").Select
End Sub

The problem is this has to be executed manually.

Based on the comments I've created the following code:

Private Sub Worksheet_Change(ByVal Target As Range)
    ' Sizes the table to include all new rows
    Application.EnableEvents = False
        If ActiveSheet.FilterMode Then ActiveSheet.AutoFilter.ShowAllData
        LastRow = ActiveSheet.Range("a1").Offset(ActiveSheet.Rows.Count - 1, 0).End(xlUp).Row
        ActiveSheet.ListObjects("TUpdate").Resize Range("$A$2:$AK$" & LastRow)
    Application.EnableEvents = True
End Sub

But the code executes when I add a value in a cell under the table, but now when I copy a row.

like image 222
Selrac Avatar asked May 03 '26 17:05

Selrac


1 Answers

You can change Excel setting to do that :

File > Options > Proofing > AutoCorrect Options > AutoFormat As You Type and check Include new rows and columns in table

Or run this line only one time:

Application.AutoCorrect.AutoExpandListRange = True
like image 102
Fadi Avatar answered May 05 '26 11:05

Fadi