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

这个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代码?

例如: =ESTAnneeBissextile("Cell Name")

你有一个语法错误。 改变Dime bReponse As Boolean Dim bReponse As Boolean ,你应该很好去。 一旦你这样做,你将能够完全按照你在(2)中指定的方式来调用它,但是当引用一个单元格时,不要引用引号。

您提供的示例中有几个问题。

  • “angular钱”应该是“昏暗的”(如ErinsMatthew所述)
  • 您的返回值被列为“ESTAnneeBissextile”,但function名称的拼写方式与“ESTAnneeBixxstile”不同。 这将导致每次都有一个FALSE结果。
  • 你的variablesinput被称为“iAnne”,但你在代码中使用的variables是“iAnnee”。 请提出使用相同的名称或结果将不准确。
  • 通过在代码顶部添加Option Explicit字样,您可以捕获这些命名问题。 🙂
  • 你的代码中的逻辑是错误的。 如果一年可以是MOD 400,那么应该是TRUE,但是在你的代码中,如果它通过了以前的两个条件,你只能得到这个检查。 请确保将该检查单独作为自己的if语句,或使用下面提供的示例。

修复这些应该使你的function正常工作。 正如评论所build议的那样,最好使用:

 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是否像我一样以上,读起来更容易,debugging更容易):

 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