当数据添加到表下方时,Excel VBA扩展表

时间:2017-03-19 09:40:19

标签: excel vba excel-vba

我在Excel中有一个表,当用户在表后添加数据时,数据不属于该表。

我创建了一个可以执行以扩展表的代码。代码如下:

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

问题是这必须手动执行。

根据评论,我创建了以下代码:

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

但是当我在表格下的单元格中添加值时,代码会执行,但现在当我复制一行时。

3 个答案:

答案 0 :(得分:1)

您可以将代码作为Worksheet_Change事件的处理程序。

Arrtice on MSDN

答案 1 :(得分:1)

您可以更改Excel设置:

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

或者只运行一次此行:

Application.AutoCorrect.AutoExpandListRange = True

答案 2 :(得分:0)