【问题标题】:vba If within ifvba 如果在如果
【发布时间】:2018-02-10 13:15:45
【问题描述】:

我想创建一个函数,根据员工的工资(下限和上限)和年龄(在 25 岁之前不缴款和64 岁以后)。

通过以下代码,我尝试实现这一目标。我可能在屏幕前花费了太多时间,但我没有发现问题。调试器运行良好,但我不断收到“#Value!”警报。它可能是另一个 If 中的 If 语句。如果有人可能会看到问题出在哪里,那将非常有帮助

Option Explicit
Constant M = 1175

Function coti_min_LPP(x As Integer, salaire_AVS As Double)

Dim salaire_coord As Double

'The basis for the calculation uses the salary in different layers
If salaire_AVS < 18 * M Then 
salaire_coord = 0
ElseIf salaire_AVS > 18 * M And salaire_AVS < 24 * M Then
salaire_coord = 3 * M
ElseIf salaire_AVS > 24 * M Then
salaire_coord = salaire_AVS - 21 * M
End If

'Under a certain limit, the contribution is a percentage of the basis 
'according to the age
If salaire_AVS < 72 * M Then
If x < 25 Then
coti_min_LPP = 0
ElseIf x > 24 And x < 35 Then
coti_min_LPP = salaire_coord * 0.07
ElseIf x > 34 And x < 45 Then
coti_min_LPP = salaire_coord * 0.1
ElseIf x > 44 And x < 55 Then
coti_min_LPP = salaire_coord * 0.15
ElseIf x > 54 And x < 65 Then
coti_min_LPP = salaire_coord * 0.18
ElseIf x > 64 Then
coti_min_LPP = 0
End If

Else
'Above the limit, it is the percentage of a fixed amount
If x < 25 Then
coti_min_LPP = 0
ElseIf x > 24 And x < 35 Then
coti_min_LPP = 51 * M * 0.07
ElseIf x > 34 And x < 45 Then
coti_min_LPP = 51 * M * 0.1
ElseIf x > 44 And x < 55 Then
coti_min_LPP = 51 * M * 0.15
ElseIf x > 54 And x < 65 Then
coti_min_LPP = 51 * M * 0.19
ElseIf x > 64 Then
coti_min_LPP = 0
End If

End If

End Function

【问题讨论】:

    标签: vba excel if-statement


    【解决方案1】:

    有两件直接的事情会导致问题:

    • 您应该使用Private Const M As Long = 1175 而不是Constant M = 1175。为什么长?请查看 If salaire_AVS &lt; 72 * M Then 行,如果您添加 watch 并在调试器中检查您的代码,您会发现,如果 M 被声明为整数,则在此行之后(根据监视窗口) M 的值“脱离上下文”。这基本上是由于您已经实现了整数溢出。请考虑以下代码:

    示例 1:

    Sub test2()
    
    Dim a As Integer
    Dim b As Double
    
    a = 1175
    b = 15 
    
    Debug.Print b < 72 * a
    
    End Sub
    

    经过上述更改后,您的功能对我有效(已测试 =coti_min_LPP(27,19*1175)

    希望对您有所帮助。顺便提一句。请注意,有这么多带有硬编码值的嵌套 if 很难维护和控制,通常不被视为良好的编码习惯。

    【讨论】:

    • 并考虑 long over integer
    • 感谢您的回答。它仍然不适用于我将常量更改为常量并删除选项显式。我在大学里了解到 Option Explicit 始终是最佳实践选择,但我并不真正理解为什么。
    • @QHarr 感谢您的意见。因此,对于任何“数字”变量,您总是使用 Long 吗?跟计算时间有关系吗?
    • 我写 =coti_min_LPP(27; 19*1175) (使用“瑞士”方式输入变量,如果它可能是问题的根源)
    • 我已经编辑了我的答案。请尝试更改您的 const 声明。
    猜你喜欢
    • 2019-02-08
    • 2019-08-03
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 2015-06-18
    • 1970-01-01
    • 2017-01-31
    • 2016-05-02
    相关资源
    最近更新 更多