Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ISO week number in VBScript or VBA

How can I get the ISO week number of some date in VBScript or VBA?

like image 851
Michel de Ruiter Avatar asked Mar 31 '26 16:03

Michel de Ruiter


1 Answers

First, note that:

  1. It is important to report the week year along with the week number, as the date's year could be different.
  2. Several Windows components contain a bug for some years' last Monday.

In my experience the simplest, clearest and most robust way to compute this is:

Sub WeekNum(someDate, isoWeekYear, isoWeekNumber, isoWeekDay)
  Dim nearestThursday
  isoWeekDay = WeekDay(someDate, vbMonday)
  nearestThursday = DateAdd("d", 4 - Int(isoWeekDay), someDate)
  isoWeekYear = Year(nearestThursday)
  isoWeekNumber = Int((nearestThursday - DateSerial(isoWeekYear, 1, 1)) / 7) + 1
End Sub

This also returns the ISO day of the week, counting from 1 for Mondays.

like image 89
Michel de Ruiter Avatar answered Apr 03 '26 09:04

Michel de Ruiter