Richard Garcia
Richard Garcia

Reputation: 7

Block If without End If Error

I just did my first If..Then basic then I tried to do logical operators to compare two values in the first two cells to result in message box. I get an End If Statement compile error

The actual code:

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

Upvotes: 0

Views: 242

Answers (3)

Danny_ds
Danny_ds

Reputation: 11406

I think you need a second End If here:

End If
End If
End Sub

If you indent your code properly, it would become visible.

Update: After proper formatting it becomes clear that you actually needed an ElseIf, see below.


Your comment: How should it typically be indented?

Well, usually, after each If you indent the block that follows, and has to be executed if the condition following that If is true - when the If statements are nested you indent more, like:

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

That way you have a good overview of the nesting, and it is harder to forget an End If.

In this case, after reformatting your code, it also becomes clear that you actually needed an ElseIf (as others already stated):

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

So good formatting of the code is important to avoid mistakes like that and keep a good overview. This also holds for loops etc.

Upvotes: 2

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200573

If you want to use the If <condition> Then <action> short notation (without an End If after the action) you MUST put the statement in one line, either by actually having the statement in a single line:

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

or by wrapping that line using the line continuation operator (_):

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

Otherwise you MUST use block syntax with an End If after the action:

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

With that said, what you actually want here is an If..ElseIf..Else statement, because you have three different, mutually exclusive, states (less, equal, greater):

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

Upvotes: 1

A.S.H
A.S.H

Reputation: 29362

The second If, I mean this line:

If firstnum < secondnum Then

should be an ElseIf :

ElseIf firstnum < secondnum Then
    ....

Upvotes: 0

Related Questions