分别在Excel的第一天和最后一天填写两列

时间:2017-03-01 08:29:34

标签: excel vba excel-vba

我希望代码能够在当月的第一天和最后一天填写A列和B列。它应该看起来像这样:

1 个答案:

答案 0 :(得分:2)

以下是查找一个月的第一天和最后一天的两个函数。填写列应该很容易。

Function dhFirstDayInMonth(Optional dtmDate As Date = 0) As Date
    ' Return the first day in the specified month.
    If dtmDate = 0 Then
        ' Did the caller pass in a date? If not, use
        ' the current date.
        dtmDate = Date
    End If
    dhFirstDayInMonth = DateSerial(Year(dtmDate), _
     Month(dtmDate), 1)
End Function


Function dhLastDayInMonth(Optional dtmDate As Date = 0) As Date
    ' Return the last day in the specified month.
    If dtmDate = 0 Then
        ' Did the caller pass in a date? If not, use
        ' the current date.
        dtmDate = Date
    End If
    dhLastDayInMonth = DateSerial(Year(dtmDate), _
     Month(dtmDate) + 1, 0)
End Function

来源:Finding the Beginning or End of a Month

要获取当前其他月份的第一个/上个月日期,您可以使用DateAdd()-function作为输入日期:

lastDayOfLastMonth = dhLastDayInMonth(DateAdd("m", -1, Date))
firstDayOfLastMonth = dhFirstDayInMonth(DateAdd("m", -1, Date))