Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Nested If statement Simple but what Am I missing?

  1. Jul 31, 2009 #1
    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 (Text):
    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
     
     
  2. jcsd
  3. Jul 31, 2009 #2
    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 (Text):
    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: Jul 31, 2009
  4. Jul 31, 2009 #3
    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.

    ?
     
  5. Jul 31, 2009 #4
    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.
     
  6. Jul 31, 2009 #5
    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 (Text):
    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
     
  7. Jul 31, 2009 #6
    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!
     
  8. Aug 8, 2009 #7
    Last edited by a moderator: May 4, 2017
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook