Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA - How the colon `:` works in VBA code with condition

Tags:

excel

vba

The colon operator : is a statement delimiter in VBA.

However, does anyone has a clue why the first three examples work and the fourth (when uncommented) produces an error?

Option Explicit

Public Sub TestMe()

    If 1 = 1 Then: Debug.Print 1

    If 2 = 2 Then Debug.Print 2

    If 3 = 3 Then:
        Debug.Print 3

'   Gives error:
'    If 4 = 4 Then
'        Debug.Print 4

'Other Examples, from the comments and the answers:

::::::::::::::::::::::::::::         '<-- This seems to be ok

    If 5 = 5 Then Debug.Print "5a"::: Debug.Print "5b"
    If 6 = 0 Then Debug.Print "6a"::: Debug.Print "6b"

    If 7 = 0 Then:
        Debug.Print 7 ' Does not have anything to do with the condition...

    If 8 = 0 Then Debug.Print "8a"::: Debug.Print "8b" Else Debug.Print "8c"

End Sub
like image 508
Vityata Avatar asked Feb 01 '17 15:02

Vityata


2 Answers

I think the confusion comes from 3. We'd think that 3 and 4 should behave the same. In fact, 3 is equivalent to this:

If 3 = 3 Then: (do nothing) 'an empty statement
   Debug.Print 3 ' <-- This will be executed regardless of the previous If condition

To see it, change 3 into this:

If 3 = 0 Then:
    Debug.Print 3 '<-- 3 will be printed! ;)

In conclusion, yes, the : is indeed to merge many statements on a single line

Good job @Vityata !!! :)

like image 161
A.S.H Avatar answered Oct 22 '22 16:10

A.S.H


If Then Blocks require a matching End If when they are multi-line.

The first case is fine because the command after Then is on the same line.

The second case is fine for the same reason, the : makes no difference in this situation.

The third case works because when the IF statement evaluates to True, there is no command following the ':'. The : signals to compiler that the next command should be seen as being on the same line. There is nothing following, so processing moves to the next line which is seen as outside the If Then Block.

The fourth case has no notation to tell the compiler that the If Then command is single line, and therefore it is looking for the End IF to the block.

Option Explicit

Public Sub TestMe()

  If 1 = 1 Then: Debug.Print 1 '<-- All on a single line - OK

  If 2 = 2 Then Debug.Print 2  '<-- All on a single line - OK

  If 3 = 3 Then:               '<-- No command following :
    Debug.Print 3              '<-- Seen as outside the If Then Block

'   Gives error:
'    If 4 = 4 Then
'        Debug.Print 4
'    End IF                   '<-- Required to show the end of the If Then block
End Sub
like image 28
Rdster Avatar answered Oct 22 '22 15:10

Rdster