简体   繁体   中英

VBA Set a specific date to be the first week of the year

I want to set a specific date (October 06 , 2014) to be the 1st Week of the year. So when I use the =weeknum() formulaR1C1 it will return the week number.

I'm currently working on a worksheet that gets updated daily so the week number will be updated every week only. In column ("D") indicates the week number. and column ("B") indicates the daily date.

If i use the =weeknum() formula on it returns the value of 41, but it needs to be week number 1.

How about creating your personalized function? It just consists of counting how many days there are between the date you insert (myDate) and the date which is considered to be the first day of the year (first_day), dividing this number by 7, taking its integer and adding up 1. It will always give you the right one.

Public Function special_weeknum(ByVal myDate As Date) As Integer

    Dim first_day As Date: first_day = #10/6/2014#
    Dim myWeek As Integer: myWeek = Int((myDate - first_day) / 7) + 1
    special_weeknum = myWeek

End Function

Please note that this approach would allow you also to pass the first day as a user input:

Public Function special_weeknum(ByVal myDate As Date, ByVal first_day As Date)
    Dim myWeek As Integer: myWeek = Int((myDate - first_day) / 7) + 1
    special_weeknum = myWeek
End Function

so that you will always be able to decide which is the day you must consider as first day of the year.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM