你是怎么在VBA找到Leapyear的?

Lan*_*rts 11 excel vba function excel-vba code-snippets

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

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

Lan*_*rts 22

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  
Run Code Online (Sandbox Code Playgroud)

我最初从Chip Pearson的Excel网站上获得了这个功能.

皮尔逊的网站

  • 实际上,如果你研究他们正在做什么,它总是有效的.他们检查2月份是否有29天,这使它成为一个整整的月份.它基本上把微软的规则都归咎于微软.芯片有很多很好的解决方案. (4认同)
  • 这并未考虑所有闰年规则。 (2认同)

sea*_*boy 14

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
Run Code Online (Sandbox Code Playgroud)

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


Bre*_*ugh 5

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

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
Run Code Online (Sandbox Code Playgroud)

  • 如果效率是目标,你可以摆脱isLeapYear = false,因为布尔值默认为false :) (2认同)