Date for Previous Monday Excel

十年热恋 提交于 2019-12-19 09:56:44

问题


Today is 02/27/2013 which is Wensday. I need formula which will return me date for previous Monday.which would be (02/17/2013)

I need to so I can use for file name or email subject in my vba code which sends emails.

With oMail
     'Uncomment the line below to hard code a recipient
     .To = "myemail@email.com"
     'Uncomment the line below to hard code a subject
     .Subject = "Current Report"
     .Attachments.Add WB.FullName
    .Display
End With

回答1:


Public Function LastMonday(pdat As Date) As Date
    LastMonday = DateAdd("ww", -1, pdat - (Weekday(pdat, vbMonday) - 1))
End Function

Weekday(yourdate, vbMonday) returns a 1 for Monday, 2 for Tuesday, etc. so

pdat - (Weekday(pdat, vbMonday) - 1)

Will give us the most recent Monday by subtracting the Weekday()-1 # of days from the passed date.

DateAdd("ww", -1, ...)

subtracts one week from that date.

LastMonday(cdate("2/27/13"))

Returns 2/18/2013 (which is Monday, not the 17th)




回答2:


Calculate the difference between Weekday(Now()) and 2 (= weekday for monday), then add 7.




回答3:


Dan's answer should cover your needs in VBA

or in Excel worksheet formula, you could do something like this:

    =TEXT(DateCell- (WEEKDAY(DateCell,2)-1),"dddd mmmm dd")

so DateCell is a range containing the date that you want to find the date of the previous Monday!

so if you put 08/04/2012 in DateCell, then that formula will retrun Monday 2nd April!

(credit to MrExcel.com and Google search!) HTH Philip




回答4:


To make the accepted answer's function a bit more versatile, a couple of minor changes lets you specify which day of week, and how far back/forward you want it.

Public Function LastDow(pdat As Date, dow as integer, _&
                optional weeksOffset = -1 as integer) As Date
    LastDow = DateAdd("ww", weeksOffset, pdat - (Weekday(pdat, dow) - 1))
End Function

With this function you can get, say, the next Wednesday:

dim myDt as date
dim nextWed as date
myDt = now()
// Get next Wednesday (dow = Wednesday, weeksOffset is +1
x = LastDow(myDt, vbWednesday, 1)

Thanks again to the original solution author (Dan Meltheus).



来源:https://stackoverflow.com/questions/15116513/date-for-previous-monday-excel

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