如何插入并拖动公式,直到Excel VBA中的最后一行

在这里输入图像说明 我想在E行的末尾插入只计算每个月的第一天(1.Nov.2017,1.Dec.2017等)的公式,并拖动到与D行的值相等的末尾。 我用下面的代码,但不工作。

只有A:D有数据,我才需要“E12:E21”中的值作为01.Nov.2017。 但A:D会自动计算。 下个月A22:D24将包含数据。 所以我需要在“E22:E24”中的值为01.2017年12月。 帮我

Private Sub CommandButton1_Click() Range("E" & Rows.Count).End(xlUp).Offset(1, 0).Select Run FirstDayInMonth() Selection.AutoFill Destination:=Range("D" & Column.count).End(xlUp).Offset(0, 1), Type:=xlFillCopy End Sub Function FirstDayInMonth(Optional dtmDate As Date = 0) As Date Range("E" & Rows.Count).End(xlUp).Offset(1, 0).Select If dtmDate = 0 Then dtmDate = Date End If FirstDayInMonth = DateSerial(Year(dtmDate), _ Month(dtmDate), 1) End Function 

起初,你过度使用select。 它只能在一种情况下在代码中使用 – 如果你希望macros在最后指向特定的单元格。 例如,看这篇文章 。
其次,避免Smart UI反模式。 什么是智能用户界面, 你可以在这里阅读 :

第三,我认为你应该使用sub,而不是在这里。

 Sub FillFirstDay(Optional dtmDate As Double = 1) Dim ws As Worksheet Dim rng As Range Dim lastRow As Long, firstRow As Long Set ws = ActiveSheet 'You should assign your sheet here, for example by name 'Then we find our range in E column With ws lastRow = .Range("D" & .Rows.Count).End(xlUp).Row firstRow = .Range("E" & .Rows.Count).End(xlUp).Row + 1 Set rng = Range(.Range("E" & firstRow), .Range("E" & lastRow)) End With If firstRow >= lastRow Then Exit Sub 'And finally add first date of month With rng .Value = DateSerial(Year(dtmDate), Month(dtmDate), 1) .NumberFormat = "yyyy-mm-dd" 'or whatever date format do you like End With End Sub 

如果firstRow> = lastRow然后Exit Sub终止E列中的date已经被填充的行。

也许我错过了这样一个理由,那就是要以复杂的方式来完成,但是不能只使用工作表函数吗?

你想要列E显示一个date(月的第一个)在有数据的行?

把它放到单元格E2(或者如果你想要的话,可以是E列的全部),直接或者通过编程(使用WorksheetFunction):

 =IF(D2="","",DATE(YEAR(NOW()),MONTH(NOW()),1)) 

修改公式:

示例公式