0
votes

Hi I'm trying to put in some UserForm validation for date range that is entered by a user.

The date range that needs to be picked is for the previous week from Monday to Sunday eg. 13 Aug 2012 to 19 Aug 2012. So if I was to run the report today (24 Aug 2012) how can I work out that the dates I need to enter in is 13 Aug 2012 to 19 Aug 2012, and what if I ran the report tomorrow.

Can I do it by working out the WeekDayName of the day I'm running the report (eg. Friday) and from that use DateAdd to subtract to the previous Monday (-11) for the first date and subtract to the previous Sunday (-5) for the second date.

So if the user was to enter the date range of 14 Aug 2012 and 19 Aug 2012, an msgbox will appear telling them that the date range that should be entered is 13 Aug 2012 to 19 Aug 2012 and do they want to continue.

Hope this makes sense.

1
If it's always one week why not just let them enter only the start date?Tim Williams

1 Answers

0
votes

This will work:

Sub testDate()

    Dim myDate As Date
    myDate = "8/14/2012"

    Dim weekStartDate As Integer
    weekStartDate = 2
    'set for the sunday -> sunday for the given date

    Dim startDate, endDate As Date
    startDate = myDate - Weekday(myDate) + weekStartDate   'take current date, find system weekstart (Sunday), adjust accordingly
    endDate = startDate + 6    'you are only adding 6 days to your week it seems?

    MsgBox ("Please select a date between " & startDate & " and " & endDate)

End Sub

When you use Weekday(myDate) it returns an integer which is the number of days which have passed since the system week start, which I believe will normally be Sunday. So Monday = 1 etc.