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 ("?" )