# Nested If statement Simple but what Am I missing?

I am learning VBA for Excel and Am just wondering what is wrong with the logic in this statement?

Note that at the present moment, Time < 0.5 , but my program is outputting "Good Evening"

Code:
Sub Better_Nested_If()
Dim Msg As String
If Time < 0.5 Then Msg = "Mornin'" Else
If Time >= 0.5 And Time < 0.75 Then Msg = "Afternoon" _
Else: Msg = "Evening"
MsgBox "Good " & Msg & "!"
End Sub

Related Programming and Computer Science News on Phys.org
Nothing is wrong with the logic but your use of the language is incorrect. You left out the "End If" and the colon after "Else" should be left out.

Also, to avoid confusion you should put "then" and "else" statements on separate lines.

Here is an example If Then Else statement:

Code:
If X < Y then
Msg = "X is less than Y"
ElseIf X > Y then
Msg = "X is greater than Y"
Else
Msg = "X is equal to Y"
End If

Last edited:
Thanks BUt here's the problem with that:

You only use End If with 'block If' statements, which this is not.

Also, this is not a nested 'ElseIf' Sub.

?

Thanks BUt here's the problem with that:

You only use End If with 'block If' statements, which this is not.

Also, this is not a nested 'ElseIf' Sub.

?
I wouldn't write the above nested like you do. It would be more readable doing how the above poster suggested. That said, maybe the "Else:" is messing up your program. If I recall correctly Colin is used to denote a label. Thus maybe the program is executing this line regardless of what happens above.

That is first perhaps it goes to your first in block and set msg=morning but then later in your program over rites it as evening. Good start if you are trying to obfuscate your code.

Thanks BUt here's the problem with that:

You only use End If with 'block If' statements, which this is not.

Also, this is not a nested 'ElseIf' Sub.

?
Yes, I realized after I made the post that you were questioning the nested If statement. Even so I believe my example is a better solution to your problem. But if you just want to use nested IFs then you could do it this way:

Code:
If X < Y then
Msg = "X is less than Y"
Else
If X > Y then
Msg = "X is greater than Y"
Else
Msg = "X is equal to Y"
End If
End If

Okay Thanks! I realize that these are poorly written loops, but they were part of an Intro to VBA text that I am using. I was just unclear as to why they did not work if they were published in the book.

Perhaps the Author did not test them all :/

Thanks again!

Last edited by a moderator: