Nested If statement Simple but what Am I missing?

  • #1
3,003
2
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
 

Answers and Replies

  • #2
887
98
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:
  • #3
3,003
2
Thanks :smile: 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.

?
 
  • #4
Thanks :smile: 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.
 
  • #5
887
98
Thanks :smile: 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
 
  • #6
3,003
2
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 :/

:smile: Thanks again!
 
  • #7
783
9
Last edited by a moderator:

Related Threads on Nested If statement Simple but what Am I missing?

Replies
11
Views
4K
Replies
18
Views
8K
Replies
18
Views
966
Replies
31
Views
3K
  • Last Post
Replies
2
Views
548
Replies
4
Views
13K
Replies
11
Views
2K
Replies
9
Views
1K
Replies
8
Views
2K
Top