VBA如果那么函数总是返回0

我和朋友在互联网上search了一个答案。 我相当新的VBA和我的function总是返回0.有些帮助,这将是伟大的。 以下是我的代码:

Function OnlineAbs(x As Date, y As Date, z As Date) If x > 0 Then If y > 0 Then result = "Online - Images" Else If z > 0 Then result = "Online - DT Images" Else result = "Online - No Images" End If End If Else result = "Abstract" End If End Function 

函数在VBA中返回有一点不同 。 设置想要返回到函数名称的值将返回该值。

 Function OnlineAbs(x As Date, y As Date, z As Date) If x > 0 Then If y > 0 Then OnlineAbs = "Online - Images" Else If z > 0 Then OnlineAbs = "Online - DT Images" Else OnlineAbs = "Online - No Images" End If End If Else OnlineAbs = "Abstract" End If End Function 

这段代码有几个问题:

  1. 一个小的语法错误:为了纠正它,保持代码变化最小,只需在函数结束之前添加一个行语句(如Siddharth Rout所build议的),即OnlineAbs = result End Function之前的OnlineAbs = result

  2. 更严重的问题是业务逻辑(可能的types不匹配)中的潜在缺陷:Excel Worksheet / VBA中的DateTimetypes具有基础值(例如,当前DateTime的工作表函数将返回: =VALUE(NOW()) = 42153.53481 ; in VBA对应的函数是CDbl(x)),对于大多数实际情况,对于1/1/1900之后的任何Date(基本值1/1/1900是1),> 0。 因此,您的function将在1/1/1900之后的任何date返回"Online - Images"

我会build议您validation您的业务逻辑。 亲切的问候