此VBA代码用于确定一年是否为闰年(结果为布尔值)。 下面是代码:
Function ESTAnneeBixxstile(iAnne As Integer) As Boolean
'//////////////////////////////////////////////////////////////
' Cette fonction détermine si une année est bissextile
' Elle retourne True (vrai ou -1) si l'année compote 366 jours,
' False (faux ou 0) sinon
Dime bReponse As Boolean
bReponse = False
If iAnnee Mod 4 = 0 Then
'///////////////////////////////////////////////////////
' Les années divisibles par 4 sont bissextiles
'///////////////////////////////////////////////////////
bReponse = True
If iAnnee Mod 100 = 0 Then
'//////////////////////////////////////////////////////
' Les années divisibles par 100 ne sont pas bissextiles.
'//////////////////////////////////////////////////////
bReponse = False
If iAnnee Mod 400 = 0 Then
'///////////////////////////////////////////////////////
' Mais les années divisibles par 400 sont bissextiles
'///////////////////////////////////////////////////////
bReponse = True
End If
End If
End If
ESTAnneeBissextile = bReponse
End Function
问题:
根据VBA当前语法(Office 2013),我的代码是否正确?编译器说存在语法错误。
如何在Excel电子表格中将VBA代码作为公式运行?
例如:=ESTAnneeBissextile("Cell Name")
答案 0 :(得分:3)
您的语法错误。将Dime bReponse As Boolean
更改为Dim bReponse As Boolean
,您应该好好去。完成此操作后,您将能够完全按照(2)中的指定调用它,但在引用单元格时不要使用引号。
答案 1 :(得分:2)
您提供的示例中存在一些问题。
修复这些应该使您的功能正常工作。正如评论中所建议的那样,最好使用:
Function leapCheck(year As Long) As Boolean
leapCheck = IsDate("2/29/" & year)
End Function
如果你想列出逻辑,另一种有趣的方式是:
Function isLeapYear(year As Long) As Boolean
If year Mod 400 = 0 Or year Mod 4 = 0 And year Mod 100 <> 0 Then
isLeapYear = True
Else
isLeapYear = False
End If
End Function
虽然我非常喜欢这两个选项,但这里有你上面提到的补丁的代码(我个人会检查你想要的条件和你不想要的条件,所以我会检查MOD 100是否&lt;&gt; ; 0,就像我上面做的那样。它更容易阅读,更容易调试):
Function ESTAnneeBixxstile(iAnne As Long) As Boolean
Dim bReponse As Boolean
If iAnne Mod 4 = 0 Then
bReponse = True
If iAnne Mod 100 = 0 Then
bReponse = False
End If
End If
If iAnne Mod 400 = 0 Then
bReponse = True
End If
ESTAnneeBixxstile = bReponse
End Function