【问题标题】:Return the 'week of the month' by the month按月返回“月中的周”
【发布时间】:2018-08-16 09:42:23
【问题描述】:

有人有按月返回“月中的星期”的功能吗?搜索到的大多数功能从一周的 1 日开始。我想按周去,即 2018 年 3 月 1 日将是 2 月的第 5 周。 3 月的第 1 周从 3 月 4 日开始。

我该怎么做?

【问题讨论】:

标签: vba ms-access


【解决方案1】:

首先找到该月日期的上一个星期日,因为该日期可能在上个月:

DateAdd("d", 1 - Weekday(DateOfMonth), DateOfMonth)

然后使用这个通用函数来查找该月的第一个星期日:

' Calculates the date of the occurrence of Weekday in the month of DateInMonth.
'
' If Occurrence is 0 or negative, the first occurrence of Weekday in the month is assumed.
' If Occurrence is 5 or larger, the last occurrence of Weekday in the month is assumed.
'
' If Weekday is invalid or not specified, the weekday of DateInMonth is used.
'
' 2016-06-09. Gustav Brock, Cactus Data ApS, CPH.
'
Public Function DateWeekdayInMonth( _
    ByVal DateInMonth As Date, _
    Optional ByVal Occurrence As Integer, _
    Optional ByVal Weekday As VbDayOfWeek = -1) _
    As Date

    Const DaysInWeek    As Integer = 7

    Dim Offset          As Integer
    Dim Month           As Integer
    Dim Year            As Integer
    Dim ResultDate      As Date

    ' Validate Weekday.
    Select Case Weekday
        Case _
            vbMonday, _
            vbTuesday, _
            vbWednesday, _
            vbThursday, _
            vbFriday, _
            vbSaturday, _
            vbSunday
        Case Else
            ' Zero, none or invalid value for VbDayOfWeek.
            Weekday = VBA.Weekday(DateInMonth)
    End Select

    ' Validate Occurence.
    If Occurrence <= 0 Then
        Occurrence = 1
    ElseIf Occurrence > 5 Then
        Occurrence = 5
    End If

    ' Start date.
    Month = VBA.Month(DateInMonth)
    Year = VBA.Year(DateInMonth)
    ResultDate = DateSerial(Year, Month, 1)

    ' Find offset of Weekday from first day of month.
    Offset = DaysInWeek * (Occurrence - 1) + (Weekday - VBA.Weekday(ResultDate) + DaysInWeek) Mod DaysInWeek
    ' Calculate result date.
    ResultDate = DateAdd("d", Offset, ResultDate)

    If Occurrence = 5 Then
        ' The latest occurrency of Weekday is requested.
        ' Check if there really is a fifth occurrence of Weekday in this month.
        If VBA.Month(ResultDate) <> Month Then
            ' There are only four occurrencies of Weekday in this month.
            ' Return the fourth as the latest.
            ResultDate = DateAdd("d", -DaysInWeek, ResultDate)
        End If
    End If

    DateWeekdayInMonth = ResultDate

End Function

最后,组装这些并使用 DateDiff 获得星期日的计数并加 1(一)获得星期数:

MonthWeekNumber = 1 + DateDiff("w", DateWeekdayInMonth(DateAdd("d", 1 - Weekday(DateOfMonth), DateOfMonth), 1, vbSunday), DateOfMonth) 

【讨论】:

  • 嗨 Gustav 工作就像一个魅力。您对查找当月第一个星期日的评论。我应该为此创建一个变量,我应该在哪里使用该变量?当我使用 MonthWeekNumber 时,似乎工作得很好。非常感谢您的帮助...
  • 抱歉,发现第一个星期日已经在 MonthWeekNumber 中。再次感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 2014-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多