VBA Convert date to week number

前端 未结 6 454
渐次进展
渐次进展 2021-01-12 12:01

In VBA I want to convert a date as 03/11/2017(DD/MM/YYYY) into the week number for that date.

Until now I have the following code:

   \'geting the d         


        
6条回答
  •  死守一世寂寞
    2021-01-12 12:28

    Using VBA, to convert a date into an isoWeeknumber, you merely need the DatePart function (where DT is the date of interest):

    isoWeekNumber = DatePart("ww", DT, vbMonday, vbFirstFourDays)
    

    If you want to use other definitions than that specified in ISO 8601, investigate some of the other options for FirstDayOfWeek and FirstWeekOfYear

    NOTE

    As pointed out by @Mike85, there is a bug in DatePart (and also in the Format) function wherein Monday may be erroneously given a weeknumber of 53 when it should be 1.

    There are a variety of workarounds.

    In Excel 2013+ (Excel for Mac 2011+) you can use for the ISO Weeknumber:

    isoWeekNumber = WorksheetFunction.isoWeekNum(dt)
    

    For earlier versions, you can test the Monday and adjust it if necessary, or you can write a separate routine.

提交回复
热议问题