【问题标题】:ElseIf Statement in VBA not applying all the conditions?VBA中的ElseIf语句不适用所有条件?
【发布时间】:2019-12-03 14:35:10
【问题描述】:

我不熟悉编码并尝试学习一些 VBA。我已经开始尝试构建简单的应用程序来帮助我学习,包括这个 BMI 计算器。

我希望根据计算出的 BMI 分数和随后的 If 和 Elseif 语句在指定的文本框中显示一条简单的字符串文本消息。

如果 BMI 分数小于 18,则文本框会根据需要显示“您体重过轻”。同样,如果 BMI 分数返回等于或大于 18 的值,则会显示“您是理想体重”。

但是,这就是遇到问题的地方。如果 BMI 分数大于 25,则继续显示“You Are The Ideal Weight”,而附加的 ElseIf 和 Else 语句似乎只是被忽略了?

谁能发现我错过了什么?我的代码显示在这里:

Option Explicit

Sub BMI()

Dim Height As Variant
Dim Weight As Variant
Dim BMI As Double

Height = Height_Input.Value
Weight = Weight_Input.Value


If IsNumeric(Height_Input.Value) And IsNumeric(Weight_Input.Value) Then

    BMI = CDbl(Weight_Input.Value) / (CDbl(Height_Input.Value) * CDbl(Height_Input.Value))

    BMI_Output.Value = BMI

Else: MsgBox ("Please Enter Numeric Values")

End If

If BMI < 18 Then
    The_Verdict.Value = "You Are Underweight"

    ElseIf 18 <= BMI < 25 Then
        The_Verdict.Value = "You Are The Ideal Weight"

        ElseIf 25 <= BMI < 30 Then
            The_Verdict.Value = "You Are OverWeight"

Else: The_Verdict.Value = "You Are Obese"

End If

If Height_Input.Value = ("") Or Weight_Input.Value = ("") Then

    The_Verdict.Value = ""

End If

End Sub

【问题讨论】:

    标签: vba if-statement


    【解决方案1】:

    18 &lt;= BMI &lt; 25 不正确的 VBA:

    18 <= BMI And BMI < 25
    

    应该是正确的方法。

    VBA 从右到左解析,所以首先它询问BMI &lt; 25 并返回 TRUE 或 FALSE。然后下一部分是问18 &lt;= TRUE,它永远不会是TRUE-1

    最终不需要小于或等于部分,因为 IF 将按顺序解析:

    If BMI < 18 Then
        The_Verdict.Value = "You Are Underweight"    
    ElseIf BMI < 25 Then
        The_Verdict.Value = "You Are The Ideal Weight"    
    ElseIf BMI < 30 Then
        The_Verdict.Value = "You Are OverWeight"    
    Else
        The_Verdict.Value = "You Are Obese"    
    End If
    

    【讨论】:

    • 非常感谢!我对这一切都很陌生,但你的回复很完美。干杯:)
    • 请通过单击答案旁边的复选标记来考虑是否正确
    猜你喜欢
    • 2015-09-12
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    相关资源
    最近更新 更多