以编程方式将下个月 (VBA) 添加到 Excel 中的动态范围 Table

Adding Next Month Programmatically (VBA) to a Dynamic Range Table in Excel

我有一个动态范围 table [定义 Table 名称 = MainTable]。我还有代码可以让我找到 DateRange 中的最后一个单元格(A 列的定义名称范围)。

Sub Last_Row_Range()
Dim nextMonth As Range
Set nextMonth = Sheets("MainTable").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
nextMonth.Select
End Sub

但是,这是我想不通的。我希望用户能够按下一个按钮 (btnNextMonth),它会自动转到 DateRange 中的最后一行,偏移 1 AND 自动 添加下个月。下面是我想要实现的目标的图片。提前谢谢大家。

尝试使用 table,而不是手动查找最后一行并插入。这是一个例子:

Sub Last_Row_Range()
    'Get reference to table
    Dim tbl As ListObject
    Set tbl = Sheets("MainTable").Range("MainTable").ListObject

    'Insert new row in table
    Dim tblRow As ListRow
    Set tblRow = tbl.ListRows.Add(AlwaysInsert:=True)

    'Increment previous date by 1 month and place in new row
    tblRow.Range(1, 1) = DateAdd("m", 1, tblRow.Range(0, 1).Value)
End Sub

测试