Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 !!! :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...