Search notes:

VBA statement: if

if then … end if

sub ifTest()

    for i = 1 to 10
    
        if i > 6 then
           debug.print "i = " & i
        end if
        
    next i

end sub
Github repository about-VBA, path: /language/statements/if/if-then.bas

if then … else … end if

sub ifTest()

    for i = 1 to 10
    
        if i > 6 then
           debug.print "yes"
        else
           debug.print "no"
        end if
        
    next i

end sub
Github repository about-VBA, path: /language/statements/if/if-else.bas

if then … elseif … end if

sub ifTest()

    for i = 1 to 10
    
        if     i > 7 then
               debug.print "i > 7"
        elseif i < 4 then
               debug.print "i < 4"
        else
               debug.print "4 <= i <= 7"
        end if
        
    next i

end sub
Github repository about-VBA, path: /language/statements/if/if-then-elseif.bas

Checking multiple conditions with logical operators

Multiple conditions can be checked using the logical operators not, and, or, xor, eqv and imp:
sub if_with_or_or_and()

    for i = 1 to 3
    for j = 1 to 3

        if  i=2 or j=2  then
               debug.print "At least on of i or j is 2"
        end if

        if  i=2 and j=2  then
            debug.print "Both, i and j are 2"
        end if

    next j
    next i

end sub
Github repository about-VBA, path: /language/statements/if/or-and.bas

Single line

If the if statement controls only one following statement, the following statement can be put on the same line as the if statement. The end if clause not necessary in such a scenario.
Multiple statements are separated with colons (:)
if fruit="apple"  then msgBox "yes"
if fruit="banana" then msgBox "yes": debug.print("The fruit is a banana")
Similarly, this is also possible with the else part. Note that in this construct, an elseif (without spaces) is not recognized.
if xyz="apple" then msgBox "yes" else msgBox "no"

if x = 1 then debug.print ("one") else if x = 2 then debug.print ("two") else if x = 3 then debug.print (3) else debug.print ("out of range")
Of course, using the underscore (VBA's line continuation character), such a «one line» if then else statement can be aligned more neatly:
if      x = 1 then debug.print ("one"  ) _
else if x = 2 then debug.print ("two"  ) _
else if x = 3 then debug.print ("three") _
else               debug.print ("?"    )

See also

The select statement.
VBA statements
Conditional compilation with #ifdef … then and #end if.

Index