程序流程 - 无法确定为何忽略/跳过ElseIf参数

时间:2017-03-13 21:35:44

标签: vba excel-vba excel

简要背景 - 下面的函数“CompareFI”比较3个数字(TRAC,BVAL,BGN)并检查一个数字是否在%范围内证实另一个数字(AllowVar)。 TRAC将被视为此层次结构中的最高来源,然后是BVAL,最后是BGN。 TRAC,BVAL,BGN将为0或数值> 0。我使用Abs()来制作范围+/-以进行比较。

问题/问题 - 我总是在If,Then,Else逻辑中思考,......如果第一个陈述不真实/不满足,程序将转到第二个陈述,然后是第三个等等。

对于此函数,第一个“If”语句正常工作。第一个“ElseIf”语句有效,除非2个数字在AllowVar之外 - 返回“#Value!”在Excel中。功能永远不会到达第二个“ElseIf”。 “Else”语句仅适用于第一个“If”。我无法弄清楚为什么如果第一个“If”有效并且“ElseIf”语句相似,为什么“Elseifs”不会像第一个“If”那样工作。

谢谢,

乔恩

Function CompareFI(TRAC As Single, BVAL As Single, BGN As Single, AllowVar As Single)

If (TRAC > 0 And BVAL > 0) And (Abs(BVAL / TRAC - 1) <= AllowVar) Then
    CompareFI = TRAC & " Case 1"

ElseIf (TRAC > 0 And BGN > 0) And (Abs(BGN / TRAC - 1) <= AllowVar) Then
    CompareFI = TRAC & " Case 2"

ElseIf (BVAL > 0 And BGN > 0) And (Abs(BGN / BVAL - 1) <= AllowVar) Then
    CompareFI = BVAL & " Case 3"

Else
    CompareFI = "Check this security"

End If


End Function

2 个答案:

答案 0 :(得分:2)

If (TRAC > 0 And BVAL > 0) And (Abs(BVAL / TRAC - 1) <= AllowVar) Then CompareFI = TRAC & " Case 1" 语句不会在VBA中短路,因此您不能像以下那样使用它们来防止除零:

TRAC > 0 And BVAL > 0

无论第一个带括号的表达式的结果如何,该代码都会检查 Abs(BVAL / TRAC - 1) <= AllowVarIf。如果您需要保护第二个条件,您需要嵌套If (TRAC > 0 And BVAL > 0) Then If (Abs(BVAL / TRAC - 1) <= AllowVar) Then CompareFI = TRAC & " Case 1" Exit Function End If End If If (TRAC > 0 And BGN > 0) Then If (Abs(BGN / TRAC - 1) <= AllowVar) Then CompareFI = TRAC & " Case 2" Exit Function End If End If If (BVAL > 0 And BGN > 0) Then If (Abs(BGN / BVAL - 1) <= AllowVar) Then CompareFI = BVAL & " Case 3" Exit Function End If End If CompareFI = "Check this security" 语句或使用其他一些流量控制或保护条款来确保您不要除以零:

string floatString = "23.532";
float actualFloat = Convert.ToSingle(floatString);

答案 1 :(得分:0)

... FYI

嵌套的elseif语句确实有效。以下测试给出了阳性结果

Sub Test()
    Dim TRAC As Single, BVAL As Single, BGN As Single, AllowVar As Single
    TRAC = 3: BVAL = 2: BGN = 1: AllowVar = 1
    Debug.Print CompareFI(TRAC, BVAL, BGN, AllowVar)
    TRAC = 3: BVAL = 12: BGN = 1: AllowVar = 1
    Debug.Print CompareFI(TRAC, BVAL, BGN, AllowVar)
    TRAC = 3: BVAL = 12: BGN = 15: AllowVar = 1
    Debug.Print CompareFI(TRAC, BVAL, BGN, AllowVar)
    TRAC = 3: BVAL = 12: BGN = 150: AllowVar = 1
    Debug.Print CompareFI(TRAC, BVAL, BGN, AllowVar)
End Sub

Function CompareFI(TRAC As Single, BVAL As Single, BGN As Single, AllowVar As Single)

    If TRAC > 0 And BVAL > 0 And Abs(BVAL / TRAC - 1) <= AllowVar Then
        CompareFI = TRAC & " Case 1"
    ElseIf TRAC > 0 And BGN > 0 And Abs(BGN / TRAC - 1) <= AllowVar Then
        CompareFI = TRAC & " Case 2"
    ElseIf BVAL > 0 And BGN > 0 And Abs(BGN / BVAL - 1) <= AllowVar Then
        CompareFI = BVAL & " Case 3"
    Else
        CompareFI = "Check this security"
    End If

End Function
  

输出

3 Case 1
3 Case 2
12 Case 3
Check this security