我想在 E 行的末尾插入仅计算每月第一天(1.Nov.2017、1.Dec.2017 等)的公式,并将其拖到等于 D 行值的末尾。我使用了下面的代码但不起作用。
仅当 A:D 有数据时,我才需要“E12 : E21”中的值作为 01.Nov.2017。但是 A:D 会自动计算。下个月 A22 :D24 将包含数据。所以我需要“E22:E24”中的值作为 01.Dec.2017。帮我
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。它应该仅在一种情况下在代码中使用 - 如果您希望宏在最后指向某个单元格。例如,请参阅这篇文章。
其次,避免智能 UI 反模式。什么是智能 UI,您可以在这里阅读:
第三,我认为你应该在这里使用 sub,而不是 function。
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
If firstRow >= lastRow Then Exit Sub 行在 E 列中的日期已经填满时终止该过程。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句