你如何在VBA中findLeapyear?

什么是VBA中的IsLeapYear函数的良好实现?

编辑:我运行的if-then和DateSerial实现迭代包装在一个计时器,和DateSerial更快的平均1-2毫秒(300次迭代5次运行,1平均单元格工作表公式也工作)。

Public Function isLeapYear(Yr As Integer) As Boolean ' returns FALSE if not Leap Year, TRUE if Leap Year isLeapYear = (Month(DateSerial(Yr, 2, 29)) = 2) End Function 

我最初从Chip Pearson伟大的Excel站点获得了这个function。

培生的网站

 public function isLeapYear (yr as integer) as boolean isLeapYear = false if (mod(yr,400)) = 0 then isLeapYear = true elseif (mod(yr,100)) = 0 then isLeapYear = false elseif (mod(yr,4)) = 0 then isLeapYear = true end function 

维基百科更多… http://en.wikipedia.org/wiki/Leap_year

如果效率是一个考虑因素,并且预期的年份是随机的,那么先做最常见的案例可能会稍微好一些:

 public function isLeapYear (yr as integer) as boolean if (mod(yr,4)) <> 0 then isLeapYear = false elseif (mod(yr,400)) = 0 then isLeapYear = true elseif (mod(yr,100)) = 0 then isLeapYear = false else isLeapYear = true end function 

作为Chip Pearson解决scheme的变体,您也可以尝试

 Public Function isLeapYear(Yr As Integer) As Boolean ' returns FALSE if not Leap Year, TRUE if Leap Year isLeapYear = (DAY(DateSerial(Yr, 3, 0)) = 29) End Function 

我在CodeToad上发现了这个有趣的一个:

 Public Function IsLeapYear(Year As Varient) As Boolean IsLeapYear = IsDate("29-Feb-" & Year) End Function 

虽然我很确定,在一个函数中使用IsDate可能比if if elseifs更慢。

 Public Function ISLeapYear(Y As Integer) AS Boolean ' Uses a 2 or 4 digit year 'To determine whether a year is a leap year, follow these steps: '1 If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5. '2 If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4. '3 If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5. '4 The year is a leap year (it has 366 days). '5 The year is not a leap year (it has 365 days). If Y Mod 4 = 0 Then ' This is Step 1 either goto step 2 else step 5 If Y Mod 100 = 0 Then ' This is Step 2 either goto step 3 else step 4 If Y Mod 400 = 0 Then ' This is Step 3 either goto step 4 else step 5 ISLeapYear = True ' This is Step 4 from step 3 Exit Function Else: ISLeapYear = False ' This is Step 5 from step 3 Exit Function End If Else: ISLeapYear = True ' This is Step 4 from Step 2 Exit Function End If Else: ISLeapYear = False ' This is Step 5 from Step 1 End If End Function 
 Public Function isLeapYear(Optional intYear As Variant) As Boolean If IsMissing(intYear) Then intYear = Year(Date) End If If intYear Mod 400 = 0 Then isLeapYear = True ElseIf intYear Mod 4 = 0 And intYear Mod 100 <> 0 Then isLeapYear = True End If End Function 

我看到很多很好的概念,这些概念表明了对date函数的额外理解和使用,这些理解和使用是非常棒的。就代码效率而言..考虑函数执行所需的机器代码

而不是复杂的date函数只使用相当快的整数函数BASICbuild立在GOTO上我怀疑像下面的东西更快

  Function IsYLeapYear(Y%) As Boolean If Y Mod 4 <> 0 Then GoTo NoLY ' get rid of 75% of them If Y Mod 400 <> 0 And Y Mod 100 = 0 Then GoTo NoLY IsYLeapYear = True 

NoLY:

  End Function 

这是另一个简单的选项。

 Leap_Day_Check = Day(DateValue("01/03/" & Required_Year) - 1) 

如果Leap_Day_Check = 28,那么它不是一个闰年,如果它是29。

VBA知道3月1日之前的一年是什么时间,所以将它定为2月28日或29日。