6diegodiego9
6diegodiego9

Reputation: 596

VBA colon ":" statement delimiter. How does it exactly work?

What exactly does the colon ":" (statement delimiter) do in VBA?

":" meant as a "newline" fails to explain this behavior:

This 3-lines code compiles successfully:

If 1 = 2 Then
    MsgBox "impossible"
Else: MsgBox "OK": End If


This 2-lines version fails with "Compile error: Else without If":

If 1 = 2 Then: MsgBox "impossible"
Else: MsgBox "OK": End If


This 1-line version fails with "Compile error: End If without block If":

If 1 = 2 Then: MsgBox "impossible": Else: MsgBox "OK": End If


So, how the meaning of ":" be exactly described, compatibly with these behavior?

Upvotes: 2

Views: 679

Answers (3)

iDevlop
iDevlop

Reputation: 25272

Colon : allows you to put 2 or more instructions on the same line.
Then has 2 syntaxes:

If expression Then instruction  'case a

or

If expression Then              'case b
   somecode
'optional Else / ElseIf
End If

It seems for your observations that Thenneeds to be the last instruction in the row to fall into case b.

i find : more useful in 2 situations:

With Select Case

Select Case x
   Case 1: DoThis
   Case 2: DoThat
End Select  

With Dim (if you don't require all Dims to be at the top of procedure)

   Dim Somevalue as long: SomeValue = 3

Upvotes: 0

GSerg
GSerg

Reputation: 78183

The colon is not a replacement for the new line.
It allows you to put several statements on one line, but this still counts as one line for the purpose of grammar.

The documentation specifically shows the use of colon with If:

With the single-line form, it is possible to have multiple statements executed as the result of an If...Then decision. All statements must be on the same line and separated by colons, as in the following statement:

If A > 10 Then A = A + 1 : B = B + A : C = C + B

Where "single-line form" is

If condition Then [ statements ] [ Else elsestatements ]

as opposed to the multi-line form

If condition Then
    [ statements ]
[ ElseIf condition-n Then
    [ elseifstatements ]]
[ Else
    [ elsestatements ]]
End If

You put several statement on one line, but you still use the single-line form of the If statement, without the End If.

Upvotes: 2

Nick
Nick

Reputation: 3845

The colon allows you to write a statement on one line, and denotes the end of a valid VBA statement.

However, some colons can be omitted ( or added automatically by the VBA editor ) depending on the occurrence of any else statements. The End if can also be omitted in some cases

For instance, your one line statement would run if it was written as:

If 1 = 2 Then MsgBox "impossible" Else: MsgBox "OK"

Note the absence of the End if. Your 2 line statement is syntactically wrong and will throw an error.

Upvotes: 0

Related Questions