Reputation: 185
I'm using form elements to create a datepicker. You can either pick a year, a month and a day. Or you can pick a year and a week. I'm struggling with the week bit.
You select a start year and a start week and then an end year and an end week.
Let's say you pick 4 as the start week and 7 as the end week. I then want Monday week 4 as the start date and Sunday week 7 as the end date.
How do I get those dates in the format YYYY-MM-DD? Don't know where to start!
What I have now is four dropdown menus. Start year, start week, end year and end week. Anyone able to point me in the right direction?
Upvotes: 0
Views: 166
Reputation: 2395
There are many, many different ways to go about this problem. I started with asking myself, "How would I get the date given the day and month?", then I worked backwards from that, with given the week number, how to get the date. The answer is pretty straight forward and involves a double For
loop and the use of Application.WorksheetFunction.WeekNum in VBA. Setting the start of week to Monday will also return the Monday of that given week so no extra effort is required for that.
Sub Convert_Dates()
'user inputs
Dim lYear As Long: lYear = 2020
Dim lWeekNum As Long: lWeekNum = 4
Dim lMonth As Long, lDay As Long
For lMonth = 1 To 12
For lDay = 1 To 31
If Application.WorksheetFunction.WeekNum(DateSerial(lYear, lMonth, lDay), vbMonday) = lWeekNum Then
Debug.Print Format(DateSerial(lYear, lMonth, lDay), "YYYY-MM-DD")
Exit Sub
End If
Next lDay
Next lMonth
End Sub
And the output is:
I am sure you can now modify this to meet your needs.
Upvotes: 1