阻止如果没有结束如果错误

时间:2017-03-15 21:43:51

标签: excel-vba if-statement vba excel

我刚刚完成了我的第一个基本If..Then,然后我尝试使用逻辑运算符来比较前两个单元格中的两个值,从而得到消息框。我收到End If语句编译错误

实际代码:

Sub Button3_Click()
    Dim firstnum As Long 
    Dim secondnum As Long

    firstnum = Cells(1, 1).Value
    secondnum = Cells(1, 2).Value

    If firstnum > secondnum Then
        MsgBox "The first number is greater"

    If firstnum < secondnum Then
        MsgBox "The second number is greater"
    Else
        MsgBox "The numbers are equal"
    End If
End Sub

3 个答案:

答案 0 :(得分:2)

我认为你需要第二个End If

End If
End If
End Sub

如果您正确缩进代码,它将变得可见。

更新:正确格式化后,您显然确实需要ElseIf,请参阅下文。

  

您的评论:它应该如何缩进?

通常,在每个If后缩进后面的块,并且如果If之后的条件为真,则必须执行 - 当If语句嵌套时缩进更多,例如:

If test1
    do something
    If test2
        do some more
    End If
End If

通过这种方式,您可以很好地了解嵌套,并且很难忘记End If

在这种情况下,重新格式化代码之后,您也会发现实际需要ElseIf(正如其他人已经说过的那样):

If test1
    do something
ElseIf test2
    do something else
Else
    last else case
End If

如此好的代码格式化对于避免这样的错误并保持良好的概述非常重要。这也适用于循环等。

答案 1 :(得分:1)

如果你想使用If <condition> Then <action>短符号(在动作之后没有End If)你必须将语句放在一行中,或者通过实际将语句放在一行中:

If firstnum > secondnum Then MsgBox "The first number is greater"

或使用行继续运算符(_)包装该行:

If firstnum > secondnum Then _
    MsgBox "The first number is greater"

否则,您必须在操作后使用End If的块语法:

If firstnum > secondnum Then
    MsgBox "The first number is greater"
End If

话虽如此,你实际想要的是If..ElseIf..Else语句,因为你有三种不同的互斥状态(少,相等,更大):

If firstnum > secondnum Then
    MsgBox "The first number is greater"
ElseIf firstnum < secondnum Then
    MsgBox "The second number is greater"
Else
    MsgBox "The numbers are equal"
End If

答案 2 :(得分:0)

第二个If,我的意思是这一行:

  

If firstnum < secondnum Then

应为ElseIf

ElseIf firstnum < secondnum Then
    ....
相关问题