IF statement syntax question (1 Viewer)

SurreyNick

Member
Local time
Today, 09:58
Joined
Feb 12, 2020
Messages
127
I'm interested to understand why the syntax of this very simple IF statement works in example A but not in example B. Even though both examples require only one resulting action Example B requires an End If block to work, whist Example A doesn't. The only difference is that in Example B the Debug.Print command is on a new line (absence of indenting is deliberate to illustrate the only difference is the carriage return). Could someone explain? Thank you.

Code:
Sub SimpleIFa()
'This code works without an End If block

    Dim Rating As Long
    Rating = 1
    
    If Rating = 0 Then Debug.Print "Rejected. Rating below minimum required"
    If Rating = 1 Then Debug.Print "Approved. Rating above minimum required"

End Sub

Sub SimpleIFb()
'This code will only work if an End If block is included

    Dim Rating As Long
    Rating = 1
    
    If Rating = 0 Then
    Debug.Print "Rejected. Rating below minimum required"
    If Rating = 1 Then
    Debug.Print "Approved. Rating above minimum required"

End Sub
 

MajP

You've got your good things, and you've got mine.
Local time
Today, 04:58
Joined
May 21, 2018
Messages
8,525
You answered your own question. That is the way the compiler works. If you make it one line it will compile if not it looks for a block. Think about it. If not the compiler would have no idea which lines of code would go with the if statement. This would be super confusing for any error check if not.
 

Ranman256

Well-known member
Local time
Today, 04:58
Joined
Apr 9, 2015
Messages
4,339
Either, put the IF as a single statement on 1 line, NO ENDIF
IF TRUE THEN BEEP

or IF "block" IF then new lines with code, BUT must end block with END IF

IF TRUE THEN
'statement 1
'statement 2
END IF


IF TRUE THEN
'statement 1
ELSE
'statement 2
END IF


Your example can be done with CASE
Code:
SELECT CASE RATING
  case 0
     Debug.Print "Rejected. Rating below minimum required"
  case 1
      Debug.Print "Approved. Rating above minimum required"
END SELECT
 

SurreyNick

Member
Local time
Today, 09:58
Joined
Feb 12, 2020
Messages
127
You answered your own question. That is the way the compiler works. If you make it one line it will compile if not it looks for a block. Think about it. If not the compiler would have no idea which lines of code would go with the if statement. This would be super confusing for any error check if not.
Ah. Yes, that makes sense. Thank you.
It's one thing to know what to do but another thing entirely to understanding why and I'm keen to learn the why.
 

Users who are viewing this thread

Top Bottom