What is a good implementation of a IsLeapYear function in VBA?
Edit: I ran the if-then and the DateSerial implementation with iterations wrapped in a timer, and the DateSerial was quicker on the average by 1-2 ms (5 runs of 300 iterations, with 1 average cell worksheet formula also working).
As a variation on the Chip Pearson solution, you could also try
Here's another simple option.
If Leap_Day_Check = 28 then it is not a leap year, if it is 29 it is.
VBA knows what the date before 1st March is in a year and so will set it to be either 28 or 29 February for us.
I originally got this function from Chip Pearson's great Excel site.
Pearson's site
If efficiency is a consideration and the expected year is random, then it might be slightly better to do the most frequent case first:
Late answer to address the performance question.
TL/DR: the Math versions are about 5x faster
I see two groups of answers here
I ran time tests on all posted answers, an discovered the Math methods are about 5x faster than the Date/Time methods.
I then did some optimization of the methods and came up with (believe it or not
Integer
is marginally faster thanLong
in this case, don't know why.)For comparison, I came up (very little difference to the posted version)
The Date/Time versions that build a date as a string were discounted as they are much slower again.
The test was to get
IsLeapYear
for years 100..9999, repeated 1000 timesResults
The test code was
I see many great concepts that indicate extra understanding and usage of date functions that are terrific to learn from... In terms of code efficiency.. consider the machine code needed for a function to execute
rather than complex date functions use only fairly fast integer functions BASIC was built on GOTO I suspect that something like below is faster
NoLY: