MS Access 2010 (Design View): return Monday of the current week with Monday as 1st day of the week

心已入冬 提交于 2019-12-06 22:26:38

Keep in mind that in this context we are working with dates, so if we do Date() - 1, we will get 1 day prior to today.

Date() ~ Today's date

DatePart(
        "w" - Weekday
        Date() - Today's date
        2 - vBMonday (Access assumes Sunday is the first day of the week, which is why this is necessary.)
        1 - vbFirstJan1 - This gets into using the first week of the year. We could have omitted this, as 1 is the default.
)

-1 - Subtract 1 from the DatePart value.

Values

Date() = 4/27/2015 (at time of this writing)
DatePart("w",Date(),2,1) = 1
DatePart("w",Date(),2,1)-1 = 0

So we have Date()-0... Okay, what's so great about that? Well, let's look at a more useful scenario where today's date is a day other than Monday.

Let's act like today is 4/28/2015 (Tuesday)

Date() = 4/28/2015
DatePart("w",Date(),2,1) = 2
DatePart("w",Date(),2,1)-1 = 1

So, from the outside, in; give me the current weekday value. (1 = Monday, 2 = Tuesday, etc.), and subtract 1 from that -> that's how many days we need to subtract from the current date to get back to the weekday value of 1 (Monday).

Here's a function that will do this:

Public Function DatePrevWeekday( _
  ByVal datDate As Date, _
  Optional ByVal bytWeekday As VbDayOfWeek = vbMonday) _
  As Date

' Returns the date of the previous weekday, as spelled in vbXxxxday, prior to datDate.
' 2000-09-06. Cactus Data ApS.

  ' No special error handling.
  On Error Resume Next

  DatePrevWeekday = DateAdd("d", 1 - Weekday(datDate, bytWeekday), datDate)

End Function

As vbMonday is 2 and your date is today, you can use the core expression in a query:

PreviousMonday: DateAdd("d",1-Weekday(Date(),2),Date())
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!