一个月的最后一周的Excel Run宏

时间:2018-09-25 10:48:25

标签: excel vba excel-vba

如果是本月的最后一周,我需要调用特定的函数。 喜欢:

    if  today = 31/09/2018 - 7 days 
    call function1
    end if 

我该怎么办?

预先感谢

2 个答案:

答案 0 :(得分:1)

首先,您需要确定哪个是月的最后一天。因此,您可以使用功能GetLastDayOfMonth,如下所示。

然后,您需要计算今天和LastDayOfMonth之间的差额,以检查它是否少于或等于7天。

Option Explicit

Public Sub IsTodayInLastWeekOfMonth()
    Dim LastDayOfMonth As Date
    LastDayOfMonth = GetLastDayOfMonth(Date) 'Date is always the date of today

    Dim DayDifference As Long
    DayDifference = DateDiff("d", Date, LastDayOfMonth)

    If DayDifference >= 0 And DayDifference <= 7 Then
        'today is less then 7 days from the end of month
    End If
End Sub

Public Function GetLastDayOfMonth(inputDate As Date) As Date
    Dim dYear As Integer
    dYear = Year(inputDate)

    Dim dMonth As Integer
    dMonth = Month(inputDate)

    GetLastDayOfMonth = DateSerial(dYear, dMonth + 1, 0)
End Function

答案 1 :(得分:0)

取决于您如何部分定义工作。您可以使用EOMONTH获取月末,然后使用DATEADD删除一周。我加了1,直到7天为止(包括一个端点)。

Option Explicit
Public Sub test()
    Dim d As Long
    d = CLng(Date)

    If d >= DateAdd("ww", -1, Application.WorksheetFunction.EoMonth(d, 0)) + 1 And d <= Application.WorksheetFunction.EoMonth(d, 0) Then
        Call yourSub
    End If   
End Sub

功能:

Option Explicit
Public Sub test()
    Dim d As Long
    d = CLng(Date)
    If IsInLastWeek(d) Then
        'Call yourSub
        MsgBox "We made it!"
    End If
End Sub
Public Function IsInLastWeek(ByVal datum As Long) As Boolean
    If datum >= DateAdd("ww", -1, Application.WorksheetFunction.EoMonth(datum, 0)) + 1 And datum <= Application.WorksheetFunction.EoMonth(datum, 0) Then
        IsInLastWeek = True
    End If
End Function