Excel VBA extend table when data added below table

2020-04-18 03:19发布

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.

3条回答
干净又极端
2楼-- · 2020-04-18 04:00

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
查看更多
来,给爷笑一个
3楼-- · 2020-04-18 04:08

You can put your code as a handler for the Worksheet_Change event.

Arrtice on MSDN

查看更多
登录 后发表回答