我的用户定义函数是否正确以及如何在Excel中使用它?

时间:2013-12-03 11:02:04

标签: excel vba excel-vba

此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

问题:

  1. 根据VBA当前语法(Office 2013),我的代码是否正确?编译器说存在语法错误。

  2. 如何在Excel电子表格中将VBA代码作为公式运行?

  3. 例如:=ESTAnneeBissextile("Cell Name")

2 个答案:

答案 0 :(得分:3)

您的语法错误。将Dime bReponse As Boolean更改为Dim bReponse As Boolean,您应该好好去。完成此操作后,您将能够完全按照(2)中的指定调用它,但在引用单元格时不要使用引号。

答案 1 :(得分:2)

您提供的示例中存在一些问题。

  • “Dime”应为“Dim”(如ErinsMatthew所述)
  • 您的返回值列为“ESTAnneeBissextile”,但函数名称的拼写方式与“ESTAnneeBixxstile”不同。这将导致每次都出现FALSE结果。
  • 您的变量输入称为“iAnne”,但您在代码中使用的变量是“iAnnee”。请使用相同的名称,否则结果将不准确。
  • 通过在代码顶部添加 Option Explicit ,您可以了解其中的一些命名问题。 :)
  • 您的代码中的逻辑错误。如果一年可以是MOD 400,则应该为TRUE,但在您的代码中,只有通过前两个条件才能进行检查。确保将该检查作为最后的if语句分开,或者使用我在下面提供的示例。

修复这些应该使您的功能正常工作。正如评论中所建议的那样,最好使用:

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