2017-02-09 40 views
1

我有一个动态范围表[Defined Table Name = MainTable]。我也有代码,它允许我找到DateRange(列A的定义名称范围)中的最后一个单元格。以编程方式将下个月(VBA)添加到Excel中的动态范围表中

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 自动增加下个月。下面是我想要实现的图片。先谢谢你们。 enter image description here

回答

1

尝试使用表格来获得优势,而不是手动查找最后一行并插入。这里有一个例子:

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 

测试

enter image description here

+0

感谢@Portland亚军。完美的作品! –