我们如何在VBA中找到" year年"?

时间:2020-03-06 14:40:21  来源:igfitidea点击:

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

编辑:我运行了if-then和DateSerial实现,并将迭代包装在计时器中,并且DateSerial平均快了1-2 ms(5次运行300次迭代,其中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网站获得此功能的。

皮尔森的网站

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

Wikipedia了解更多...
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

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

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

尽管我很确定在函数中使用IsDate可能比if,elseifs慢一些。