簡體   English   中英

我的用戶定義函數是否正確以及如何在Excel中使用它?

[英]Is my user-defined function correct and how to use it in Excel?

此VBA代碼用於確定年份是否為a年(結果是布爾值)。 在代碼下方:

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)中指定的方式來調用它,但是在引用單元格時不要使用引號。

您提供的示例中存在一些問題。

  • “ Dime”應為“ Dim”(如上文ErinsMatthew所述)
  • 您的返回值列為“ ESTAnneeBissextile”,但函數名稱的拼寫不同為“ ESTAnneeBixxstile”。 每次都會導致結果為假。
  • 您的變量輸入名為“ 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 <> 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM